How to print the Contents of a Panel - vb.net

How do I print the contents of a panel in vb.net, VS-2010 Winform.
I tried the code provided here but for some reason its not working.
I am trying to print the Form inside the panel

Declare Auto Function SendMessage Lib "user32" ( _
ByVal hWnd As IntPtr, _
ByVal Msg As Integer, _
ByVal wParam As IntPtr, _
ByVal lParam As Integer) As Integer
Private Enum EDrawingOptions As Integer
PRF_CHECKVISIBLE = &H1
PRF_NONCLIENT = &H2
PRF_CLIENT = &H4
PRF_ERASEBKGND = &H8
PRF_CHILDREN = &H10
PRF_OWNED = &H20
End Enum
Private Function PrintPanel()
Const WM_PRINT As Integer = &H317
Dim myBmp As Bitmap
Dim myGraphics As Graphics
Dim hdc As System.IntPtr
myBmp = New Bitmap( _
Me.FormsDispPanel.DisplayRectangle.Width, _
Me.FormsDispPanel.DisplayRectangle.Height)
myGraphics = Graphics.FromImage(myBmp)
myGraphics.DrawRectangle(Pens.White, New Rectangle(0, 0,
Me.FormsDispPanel.DisplayRectangle.Width, Me.FormsDispPanel.DisplayRectangle.Height))
hdc = myGraphics.GetHdc
'"FormsDispPanel" is your PAnel to print
Call SendMessage(FormsDispPanel.Handle, WM_PRINT, hdc, _
EDrawingOptions.PRF_CHILDREN Or _
EDrawingOptions.PRF_CLIENT Or _
EDrawingOptions.PRF_NONCLIENT Or _
EDrawingOptions.PRF_OWNED)
myGraphics.ReleaseHdc(hdc)
myBmp.Save("d:\out.bmp")
myGraphics.Dispose()
myGraphics = Nothing
myBmp = Nothing
End Function

Related

How to Add an icon on the titlebar?

Below code working fine to Minimize userform to task bar, but don't know how to insert image work. Getting error on Sub AddIcon(myForm)
Sub AddIcon(myForm)
#If VBA7 Then
Dim hWnd As LongPtr
Dim lngRet As LongPtr
#Else
Dim hWnd As Long
Dim lngRet As Long
#End If
Dim hIcon As Long
'hIcon = Sheet1.Image1.Picture.Handle
hWnd = FindWindow(vbNullString, myForm.Caption)
lngRet = SendMessage(hWnd, WM_SETICON, ICON_SMALL, ByVal hIcon)
lngRet = SendMessage(hWnd, WM_SETICON, ICON_BIG, ByVal hIcon)
lngRet = DrawMenuBar(hWnd)
End Sub
Sub AddMinimizeButton()
#If VBA7 Then
Dim hWnd As LongPtr
#Else
Dim hWnd As Long
#End If
hWnd = GetActiveWindow
Call SetWindowLongPtr(hWnd, GWL_STYLE, _
GetWindowLongPtr(hWnd, GWL_STYLE) Or _
WS_MINIMIZEBOX)
Call SetWindowPos(hWnd, 0, 0, 0, 0, 0, _
SWP_FRAMECHANGED Or _
SWP_NOMOVE Or _
SWP_NOSIZE)
End Sub
Sub AppTasklist(myForm)
'Add this userform into the Task bar
#If VBA7 Then
Dim WStyle As LongPtr
Dim Result As LongPtr
Dim hWnd As LongPtr
#Else
Dim WStyle As Long
Dim Result As Long
Dim hWnd As Long
#End If
hWnd = FindWindow(vbNullString, myForm.Caption)
WStyle = GetWindowLongPtr(hWnd, GWL_EXSTYLE)
WStyle = WStyle Or WS_EX_APPWINDOW
Result = SetWindowPos(hWnd, HWND_TOP, 0, 0, 0, 0, _
SWP_NOMOVE Or _
SWP_NOSIZE Or _
SWP_NOACTIVATE Or _
SWP_HIDEWINDOW)
Result = SetWindowLongPtr(hWnd, GWL_EXSTYLE, WStyle)
Result = SetWindowPos(hWnd, HWND_TOP, 0, 0, 0, 0, _
SWP_NOMOVE Or _
SWP_NOSIZE Or _
SWP_NOACTIVATE Or _
SWP_SHOWWINDOW)
End Sub

OpenFileDialog pre select a file

I have a form wich call OpenFileDialog.
I want a certain file to be focused in advance (Highlighted) in the files pane.
Is it possible?
I have code where i can select all files, now i want 1 file to be selected.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim OpenFileDialog1 As New OpenFileDialog
OpenFileDialog1.Filter = "All files (*.*)|*.*"
OpenFileDialog1.RestoreDirectory = True
OpenFileDialog1.FileName = "C:\MyFile.wmv"
OpenFileDialog1.InitialDirectory = My.Settings.VideoDirectory
OpenFileDialog1.Multiselect = True
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
My.Settings.VideoDirectory = Path.GetDirectoryName(OpenFileDialog1.FileName)
End If
End Sub
Dim m_lastDialogHandle As IntPtr
Public Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
Public Declare Function FindWindowExW Lib "user32.dll" (ByVal hWndParent As IntPtr, ByVal hWndChildAfter As IntPtr, <MarshalAs(UnmanagedType.LPWStr)> ByVal lpszClass As String, <MarshalAs(UnmanagedType.LPWStr)> ByVal lpszWindow As String) As IntPtr
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
MyBase.WndProc(m)
If m.Msg = 289 Then ' Notify of message loop
Dim dialogHandle As IntPtr = m.LParam
If (dialogHandle <> m_lastDialogHandle) Then
Dim hChild1 As IntPtr = 0
Dim hChild2 As IntPtr = 0
Dim hChild3 As IntPtr = 0
m_lastDialogHandle = dialogHandle
hChild1 = FindWindowExW(dialogHandle, 0, "DUIViewWndClassName", Nothing)
If hChild1 = 0 Then Exit Sub
hChild1 = FindWindowExW(hChild1, 0, "DirectUIHWND", Nothing)
If hChild1 = 0 Then Exit Sub
Do
hChild2 = FindWindowExW(hChild1, hChild2, Nothing, Nothing)
If hChild2 = 0 Then Exit Sub
hChild3 = FindWindowExW(hChild2, 0, "SHELLDLL_DefView", "ShellView")
Loop Until hChild3 <> 0
SendMessage(hChild3, &H111, &H17021, 0)
End If
End If
End Sub
End Class
I'm sure it is possible to select 1 file, i just have to know the good WM_COMMAND.
Any help will be appreciated.
Set the FileName and DefaultExt properties of your dialog before calling ShowDialog so this will pre-select MyFile in your Videos folder. This will open a file of that name with either no extension or wmv. Any other extension should fail.
Dim OpenFileDialog1 As New OpenFileDialog
OpenFileDialog1.Filter = "All files (*.*)|*.*"
OpenFileDialog1.RestoreDirectory = True
OpenFileDialog1.FileName = "MyFile"
OpenFileDialog1.DefaultExt = "wmv"
OpenFileDialog1.InitialDirectory = My.Settings.VideoDirectory
OpenFileDialog1.Multiselect = True
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
My.Settings.VideoDirectory = Path.GetDirectoryName(OpenFileDialog1.FileName)
End If
I found myself the solution with implementation of IShellBrowser, IShellView and IShellFolder. The question can be closed now.

vb.net camera pinvoke error

This question may have been asked before but im just starting out with VB.Net and was given this application to fix that uses the webcam of the pc/ tablet but I cant figure out the pinvoke error
here is my code:
Imports System.IO
Public Class frm
CaptureWebCam
Const CAP As Short = &H400S
Const CAP_DRIVER_CONNECT As Integer = CAP + 10
Const CAP_DRIVER_DISCONNECT As Integer = CAP + 11
Const CAP_EDIT_COPY As Integer = CAP + 30
Const CAP_SET_PREVIEW As Integer = CAP + 50
Const CAP_SET_PREVIEWRATE As Integer = CAP + 52
Const CAP_SET_SCALE As Integer = CAP + 53
Const WS_CHILD As Integer = &H40000000
Const WS_VISIBLE As Integer = &H10000000
Const SWP_NOMOVE As Short = &H2S
Const SWP_NOSIZE As Short = 1
Const SWP_NOZORDER As Short = &H4S
Const HWND_BOTTOM As Short = 1
Dim iDevice As Integer = 0 ' Normal device ID
Dim hHwnd As Integer ' Handle value to preview window
Public image_base64String As String
' Declare function from AVI capture DLL.
Declare Auto Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Integer, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Object) As Integer
Declare Auto Function SetWindowPos Lib "user32" Alias "SetWindowPos" (ByVal hwnd As Integer, ByVal hWndInsertAfter As Integer, ByVal x As Integer, ByVal y As Integer, ByVal cx As Integer, ByVal cy As Integer, ByVal wFlags As Integer) As Integer
Declare Auto Function DestroyWindow Lib "user32" (ByVal hndw As Integer) As Boolean
Declare Auto Function capCreateCaptureWindowA Lib "avicap32.dll" (ByVal lpszWindowName As String, ByVal dwStyle As Integer, ByVal x As Integer, ByVal y As Integer, ByVal nWidth As Integer, ByVal nHeight As Short, ByVal hWndParent As Integer, ByVal nID As Integer) As Integer
Private Sub OpenForm()
Dim iHeight As Integer = picCapture.Height
Dim iWidth As Integer = picCapture.Width
' Open Preview window in picturebox .
' Create a child window with capCreateCaptureWindowA so you can display it in a picturebox.
hHwnd = capCreateCaptureWindowA(iDevice, WS_VISIBLE Or WS_CHILD, 0, 0, 600, 480, picCapture.Handle, IntPtr.Zero)
' Connect to device
If SendMessage(hHwnd, CAP_DRIVER_CONNECT, iDevice, IntPtr.Zero) Then
' Set the preview scale
SendMessage(hHwnd, CAP_SET_SCALE, True, IntPtr.Zero)
' Set the preview rate in milliseconds
SendMessage(hHwnd, CAP_SET_PREVIEWRATE, 66, IntPtr.Zero)
' Start previewing the image from the camera
SendMessage(hHwnd, CAP_SET_PREVIEW, True, IntPtr.Zero)
' Resize window to fit in picturebox
SetWindowPos(hHwnd, HWND_BOTTOM, 0, 0, picCapture.Width, picCapture.Height, SWP_NOMOVE Or SWP_NOZORDER)
Else
' Error connecting to device close window
DestroyWindow(hHwnd)
End If
End Sub
Private Function btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapture.Click
Dim data As IDataObject
Dim bmap As Image
' Copy image to clipboard
SendMessage(hHwnd, CAP_EDIT_COPY, 0, 0)
' Get image from clipboard and convert it to a bitmap
data = Clipboard.GetDataObject()
If data.GetDataPresent(GetType(System.Drawing.Bitmap)) Then
bmap = CType(data.GetData(GetType(System.Drawing.Bitmap)), Image)
picCapture.Image = bmap
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "Jpeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif"
saveFileDialog1.Title = "Save an Image File"
saveFileDialog1.FileName = "Image001"
If saveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
' If the file name is not an empty string open it for saving.
If saveFileDialog1.FileName <> "" Then
' Saves the Image via a FileStream created by the OpenFile method.
Dim fs As System.IO.FileStream = CType(saveFileDialog1.OpenFile(), System.IO.FileStream)
picCapture.Image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg)
fs.Close()
End If
End If
End If
End Function
Public Function getImage() As String
Dim bmap As Image
Dim ms As New MemoryStream
bmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim bytes() As Byte = ms.ToArray
' Dim image_base64String As String = Convert.ToBase64String(bytes)
image_base64String = Convert.ToBase64String(bytes)
'MsgBox(image_base64String)
Return image_base64String
End Function
Private Sub frmcap_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Leave
' Disconnect from device
SendMessage(hHwnd, CAP_DRIVER_DISCONNECT, iDevice, 0)
' close window
DestroyWindow(hHwnd)
End Sub
Private Sub frmCaptureWebCam_Load(sender As Object, e As EventArgs) Handles MyBase.Load
OpenForm()
End Sub
End Class
you will notice that I'm also trying to return the image via the image_base64 variable
Can someone help me with the code as I get the following error:
PInvokeStackImbalance was detected
Message: A call to PInvoke function
'GCOS3_Mobile_Host_Application!GCOS3_Mobile_Host_Application.frmCaptureWebCam::SendMessage'
has unbalanced the stack. This is likely because the managed PInvoke
signature does not match the unmanaged target signature. Check that
the calling convention and parameters of the PInvoke signature match
the target unmanaged signature.
SendMessage declaration according to pinvoke should be like this
Declare Auto Function SendMessage Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
Also see the tips for Overloads there.
In your code you have declared lParam, which provides additional message-specific information, as object.
And you are passing IntPtr.Zero, so I think using ByVal lParam As IntPtr will be more specific.
I used the emgu library and got it to return the base 64 string:
Imports Emgu.CV
Imports Emgu.CV.Util
Imports System.IO
Public Class frmEmguCapture
Private imagecapture As Capture
Private imageCaptureReady As Boolean = False
Public b64 As String
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles tmrUpdateImage.Tick
tmrUpdateImage.Enabled = False
If imageCaptureReady Then
pbWebCamStream.Visible = True
lblConnecting.Visible = False
btnCapture.Enabled = True
pbWebCamStream.Image = imagecapture.QueryFrame.Bitmap
tmrUpdateImage.Enabled = True
Else
MessageBox.Show("Error connecting to camera.", "Error conecting to camera.", MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End If
End Sub
Public Function btnCapture_Click(sender As Object, e As EventArgs) Handles btnCapture.Click
tmrUpdateImage.Enabled = False
pbWebCamStream.Visible = True
lblConnecting.Visible = False
btnCapture.Enabled = True
pbWebCamStream.Image = imagecapture.QueryFrame.Bitmap
Dim bmap As Image
bmap = imagecapture.QueryFrame.Bitmap
Dim ms As New MemoryStream
bmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim bytes() As Byte = ms.ToArray
Dim image_base64String As String = Convert.ToBase64String(bytes)
image_base64String = Convert.ToBase64String(bytes)
b64 = image_base64String
imagecapture.Dispose()
Me.Close()
'MsgBox(image_base64String)
Return image_base64String
End Function
Private Sub frmEmguCapture_Load(sender As Object, e As EventArgs) Handles MyBase.Load
tmrLoad.Enabled = True
End Sub
Private Sub tmrLoad_Tick(sender As Object, e As EventArgs) Handles tmrLoad.Tick
tmrLoad.Enabled = False
Try
imagecapture = New Capture
imageCaptureReady = True
tmrUpdateImage.Enabled = True
Catch ex As Exception
MessageBox.Show("Error connecting to camera.", "Error conecting to camera.", MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End Try
End Sub
End Class

Error: [Expression expected] using ByVal modifier

I was hoping to get help from you, because I am encountering errors for a project using VB.net. I am having errors in using the ByVal modifier. And the 7 errors all says "Expression Expected".
I get Errors on lines 97, 103, 103, 112, 112, 146, and 146. A total of 7 Errors.
Here they are:
97:
ret = VirtualQueryEx(hProcess, ByVal lpMem, mbi, lLenMBI)
103:
ReadProcessMemory(hProcess, ByVal mbi.BaseAddress, ByVal sBuffer, mbi.RegionSize, lWritten)
112:
Call WriteProcessMemory(hProcess, ByVal CalcAddress - 1, ByVal sReplaceString, Len(sReplaceString), lWritten)
146:
test_hwnd = FindWindow(ByVal 0&, ByVal 0&)
Here is the complete code:
Option Explicit On
Imports System.Text
Imports System
Imports Microsoft.VisualBasic
Public Class Form1
Public Structure OSVERSIONINFO
Dim dwOSVersionInfoSize As Long
Dim dwMajorVersion As Long
Dim dwMinorVersion As Long
Dim dwBuildNumber As Long
Dim dwPlatformId As Long
Dim szCSDVersion As String ' 128
End Structure
Public Structure MEMORY_BASIC_INFORMATION ' 28 bytes
Dim BaseAddress As Long
Dim AllocationBase As Long
Dim AllocationProtect As Long
Dim RegionSize As Long
Dim State As Long
Dim Protect As Long
Dim lType As Long
End Structure
Public Structure SYSTEM_INFO ' 36 Bytes
Dim dwOemID As Long
Dim dwPageSize As Long
Dim lpMinimumApplicationAddress As Long
Dim lpMaximumApplicationAddress As Long
Dim dwActiveProcessorMask As Long
Dim dwNumberOrfProcessors As Long
Dim dwProcessorType As Long
Dim dwAllocationGranularity As Long
Dim wProcessorLevel As Integer
Dim wProcessorRevision As Integer
End Structure
Private Declare Function GetVersionEx Lib "kernel32" Alias "GetVersionExA" (ByVal LpVersionInformation As OSVERSIONINFO) As Long
Private Declare Function VirtualQueryEx& Lib "kernel32" (ByVal hProcess As Long, ByVal lpAddress As Short, <System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.AsAny)> ByVal o As Object, ByVal lpBuffer As MEMORY_BASIC_INFORMATION, ByVal dwLength As Long)
Private Declare Sub GetSystemInfo Lib "kernel32" (ByVal lpSystemInfo As SYSTEM_INFO)
Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal blnheritHandle As Long, ByVal dwAppProcessId As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Declare Function ReadProcessMemory Lib "kernel32" (ByVal hProcess As Long, ByVal lpBaseAddress As Short, <System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.AsAny)> ByVal o As Object, ByVal lpBuffer As Short, <System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.AsAny)> ByVal o As Object, ByVal nSize As Long, ByVal lpNumberOfBytesWritten As Long) As Long
Private Declare Function WriteProcessMemory Lib "kernel32" (ByVal hProcess As Long, ByVal lpBaseAddress As Short, <System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.AsAny)> ByVal o As Object, ByVal lpBuffer As Short, <System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.AsAny)> ByVal o As Object, ByVal nSize As Long, ByVal lpNumberOfBytesWritten As Long) As Long
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hWnd As Long, ByVal lpdwProcessId As Long) As Long
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As Long, ByVal lpWindowName As Long) As Long
Private Declare Function GetParent Lib "user32" (ByVal hWnd As Long) As Long
Private Declare Function GetWindow Lib "user32" (ByVal hWnd As Long, ByVal wCmd As Long) As Long
Const GW_HWNDNEXT = 2
Private Declare Function InvalidateRect Lib "user32" (ByVal hWnd As Long, ByVal lpRect As Long, ByVal bErase As Long) As Long
Const PROCESS_VM_READ = (&H10)
Const PROCESS_VM_WRITE = (&H20)
Const PROCESS_VM_OPERATION = (&H8)
Const PROCESS_QUERY_INFORMATION = (&H400)
Const PROCESS_READ_WRITE_QUERY = PROCESS_VM_READ + PROCESS_VM_WRITE + PROCESS_VM_OPERATION + PROCESS_QUERY_INFORMATION
Const MEM_PRIVATE& = &H20000
Const MEM_COMMIT& = &H1000
'================================================================================================================================================================='
'===============================================================Start of FUNCTION CODES==========================================================================='
'================================================================================================================================================================='
'Add 3 labels, 3 textboxes and 1 commandbutton on form
Private Sub Command1_Click()
Dim srcEncoding As Encoding
Dim dstEncoding As Encoding
Dim bytes As Byte()
Dim returnValue As Byte()
Dim pid As Long, hProcess As Long, hWin As Long
Dim lpMem As Long, ret As Long, lLenMBI As Long
Dim lWritten As Long, CalcAddress As Long, lPos As Long
Dim sBuffer As String
Dim sSearchString As String, sReplaceString As String
Dim si As SYSTEM_INFO
Dim mbi As MEMORY_BASIC_INFORMATION
sSearchString = Text2.Text
sReplaceString = Text3.Text & Chr(0)
pid = Shell(Text1.Text) 'launch application (calc.exe in this sample)
hWin = InstanceToWnd(pid) 'get handle of launched window - only to repaint it after changes
'Open process with required access
hProcess = OpenProcess(PROCESS_READ_WRITE_QUERY, False, pid)
lLenMBI = Len(mbi)
'Determine applications memory addresses range
Call GetSystemInfo(si)
lpMem = si.lpMinimumApplicationAddress
'Scan memory
Do While lpMem < si.lpMaximumApplicationAddress
mbi.RegionSize = 0
ret = VirtualQueryEx(hProcess, ByVal lpMem, mbi, lLenMBI)
If ret = lLenMBI Then
If ((mbi.lType = MEM_PRIVATE) And (mbi.State = MEM_COMMIT)) Then ' this block is In use by this process
If mbi.RegionSize > 0 Then
sBuffer = String.Equals(mbi.RegionSize, 0)
'Read region into string
ReadProcessMemory(hProcess, ByVal mbi.BaseAddress, ByVal sBuffer, mbi.RegionSize, lWritten)
'Check if region contain search string
lPos = InStr(1, sBuffer, sSearchString, vbTextCompare)
If lPos Then
CalcAddress = mbi.BaseAddress + lPos
Me.Show()
ret = MsgBox("Search string was found at address " & CalcAddress & "." & vbCrLf & "Do you want to replace it?", vbInformation + vbYesNo, "VB-O-Matic")
If ret = vbYes Then
'Replace string in virtual memory
Call WriteProcessMemory(hProcess, ByVal CalcAddress - 1, ByVal sReplaceString, Len(sReplaceString), lWritten)
'Redraw window
InvalidateRect(hWin, 0, 1)
End If
Exit Do
End If
End If
End If
'Increase base address for next searching cicle. Last address may overhead max Long value (Windows use 2GB memory, which is near max long value), so add Error checking
On Error GoTo Finished
lpMem = mbi.BaseAddress + mbi.RegionSize
On Error GoTo 0
Else
Exit Do
End If
Loop
Finished:
CloseHandle(hProcess)
End Sub
Private Sub Form_Load()
'Caption = "VB-O-Matic"
Label1.Text = "Start application:"
Label2.Text = "String to find:"
Label3.Text = "Replace with:"
Text1.Text = "Calc.exe"
Text2.Text = "Backspace"
Text3.Text = "VB-O-Matic"
Command1.Text = "&Launch It!"
End Sub
Private Function InstanceToWnd(ByVal target_pid As Long) As Long
Dim test_hwnd As Long
Dim test_pid As Long
Dim test_thread_id As Long
test_hwnd = FindWindow(ByVal 0&, ByVal 0&)
Do While test_hwnd <> 0
If GetParent(test_hwnd) = 0 Then
test_thread_id = GetWindowThreadProcessId(test_hwnd, test_pid)
If test_pid = target_pid Then
InstanceToWnd = test_hwnd
Exit Do
End If
End If
test_hwnd = GetWindow(test_hwnd, GW_HWNDNEXT)
Loop
End Function
End Class
Remove the ByVals in your function calls. Those functions already have their parameters declared as ByVal - you don't need to put ByVal in the calls to those functions as well.

vb.net generalized thread safe windows.form

''//begin cross threaded component
Private Sub dBgRIDvIEWNotInvokeRequired(ByVal dBGridViewcomponentname As DataGridView, ByVal dvalue As String)
dBGridViewcomponentname.Text = dvalue
dBGridViewcomponentname.Update()
End Sub
Private Delegate Sub deldBGrridView(ByVal dBGridViewcomponentname As DataGridView, ByVal dvalue As String)
Private Sub ThreadedDbGridViewAddress(ByVal dBGridViewcomponentname As DataGridView, ByVal dvalue As String)
Try
If InvokeRequired Then
Dim udd As New deldBGrridView(AddressOf ThreadedDbGridViewAddress)
Invoke(udd, New Object() {dBGridViewcomponentname, dvalue})
Else
dBgRIDvIEWNotInvokeRequired(dBGridViewcomponentname, dvalue)
End If
Catch ex As Exception
End Try
End Sub
Private CrossThreadedDbGridView As New deldBGrridView(AddressOf ThreadedDbGridViewAddress)
''//end cross threaded component
when used is like this CrossThreadedDbGridView(DataGridView1, "TheText")
But what if I have lots of member or property to used like this code:
DbGridPapers.ColumnCount = 5
DbGridPapers.RowCount = rc
DbGridPapers.Update()
DbGridPapers.Columns(0).HeaderText = "PaperSize"
DbGridPapers.Columns(1).HeaderText = "#of_Pages"
DbGridPapers.Columns(2).HeaderText = "#of_Images"
DbGridPapers.Columns(3).HeaderText = "Payable"
DbGridPapers.Columns(4).HeaderText = "CountedImage"
DbGridPapers.Update()
DbGridPapers.Rows(rc).HeaderCell.Value = FileName
DbGridPapers.Rows(rc).Cells(0).Value = xpapersize
DbGridPapers.Rows(rc).Cells(1).Value = xpNumbers
DbGridPapers.Rows(rc).Cells(2).Value = xiNumbers
DbGridPapers.Rows(rc).Cells(3).Value = xTotImageCounts
DbGridPapers.Rows(rc).Cells(4).Value = xTotImageCounts
DbGridPapers.Update()
What should I do to make this simple and generally a nice thread safe component
Any ideas? that I can call them like this:
CrossThreadedDbGridView(DataGridView1.ColumnCount, 5)
CrossThreadedDbGridView(DataGridView1.RowCount, rc)
CrossThreadedDbGridView(DataGridView1.Columns(0).HeaderText, "PaperSize")
...
...
Or is there a better way of doing this
''//It's not really a generalized safe thread datagridview, i just input the details to run safely.
''//This is a bad programming code style I know, but there's many way to kill a chicken.
''//begin cross threaded DataGridView component
Private Sub dBgRIDvIEWNotInvokeRequired(ByVal yselect As Integer, ByVal dBGridViewcomponentname As DataGridView, _
ByVal dvalue As Integer, ByVal yfilename As String, ByVal ypapersize As String, _
ByVal ynumpages As Integer, ByVal yimagecount As Integer, ByVal yregularprice As Decimal, ByVal ycountedimages As Integer)
If yselect = 1 Then
dBGridViewcomponentname.ColumnCount = 5
dBGridViewcomponentname.RowCount = dvalue
dBGridViewcomponentname.Update()
dBGridViewcomponentname.Columns(0).HeaderText = "PaperSize"
dBGridViewcomponentname.Columns(1).HeaderText = "Charge_Pages"
dBGridViewcomponentname.Columns(2).HeaderText = "#of_Images"
dBGridViewcomponentname.Columns(3).HeaderText = "Payable"
dBGridViewcomponentname.Columns(4).HeaderText = "CountedImage"
dBGridViewcomponentname.Update()
ElseIf yselect = 2 Then
dBGridViewcomponentname.Rows(dvalue).ErrorText = yfilename
dBGridViewcomponentname.Rows(dvalue).HeaderCell.Value = yfilename
dBGridViewcomponentname.Rows(dvalue).Cells(0).Value = ypapersize
dBGridViewcomponentname.Rows(dvalue).Cells(1).Value = ynumpages
dBGridViewcomponentname.Rows(dvalue).Cells(2).Value = yimagecount
dBGridViewcomponentname.Rows(dvalue).Cells(3).Value = yregularprice
dBGridViewcomponentname.Rows(dvalue).Cells(4).Value = ycountedimages
dBGridViewcomponentname.Update()
ElseIf yselect = 3 Then
dBGridViewcomponentname.Update()
ElseIf yselect = 4 Then
dBGridViewcomponentname.Rows.RemoveAt(dvalue)
End If
End Sub
Private Sub CrossThreadedDbGridView(ByVal yselect As Integer, ByVal dBGridViewcomponentname As DataGridView, _
ByVal dvalue As Integer, ByVal yfilename As String, ByVal ypapersize As String, _
ByVal ynumpages As Integer, ByVal yimagecount As Integer, ByVal yregularprice As Decimal, ByVal ycountedimages As Integer)
Try
If InvokeRequired Then
Dim udd As New deldBGrridView(AddressOf CrossThreadedDbGridView)
Invoke(udd, New Object() {yselect, dBGridViewcomponentname, dvalue, yfilename, ypapersize, ynumpages, yimagecount, yregularprice, ycountedimages})
Else
dBgRIDvIEWNotInvokeRequired(yselect, dBGridViewcomponentname, dvalue, yfilename, ypapersize, ynumpages, yimagecount, yregularprice, ycountedimages)
End If
Catch ex As Exception
End Try
End Sub
Private Delegate Sub deldBGrridView(ByVal yselect As Integer, ByVal dBGridViewcomponentname As DataGridView, _
ByVal dvalue As Integer, ByVal yfilename As String, ByVal ypapersize As String, _
ByVal ynumpages As Integer, ByVal yimagecount As Integer, ByVal yregularprice As Decimal, ByVal ycountedimages As Integer)
''//end cross threaded DataGridView component
''//usage:
CrossThreadedDbGridView(2, DbGridPapers, rc, FileName, xpapersize, xpNumbers, xiNumbers, ((xRegularPrice * xpNumbers) + xTotImageCounts), xTotImageCounts)