Reputation: 1221
I would like to know how to capture right click and paste option through mouse click. It is a winforms application. I would be modifying the contents of clipboard before pasting. I am able to perform this through ctrl+V but not able to find a way to handle mouse right click.
I have tried this so far:
Private Const WM_PASTE As Integer = &H302
Protected Overrides Sub WndProc(ByRef msg As Message)
If msg.Msg = WM_PASTE AndAlso Clipboard.ContainsText() Then
Clipboard.SetText(Clipboard.GetText().Replace(vbCrLf, " "))
End If
MyBase.WndProc(msg)
End Sub
Upvotes: 2
Views: 3454
Reputation: 1221
I found this to be working like awesome:
<System.Runtime.InteropServices.DllImport("user32.dll", SetLastError:=True)> _
Private Shared Function FindWindowEx(hwndParent As IntPtr, hwndChildAfter As IntPtr, lpszClass As String, lpszWindow As String) As IntPtr
End Function
Private Sub SearchCriteria_MouseDown(sender As Object, e As MouseEventArgs) Handles SearchCriteria.MouseDown
Dim lhWnd As IntPtr = FindWindowEx(SearchCriteria.Handle, IntPtr.Zero, "EDIT", Nothing)
If e.Button = Windows.Forms.MouseButtons.Right And lhWnd <> 0 Then
Clipboard.SetText(Clipboard.GetText().Replace(vbCrLf, " "))
End If
End Sub
Upvotes: 0
Reputation: 101162
You have to process the WM_PASTE
windows message using WndProc
(a list of all messages can be found here).
For example, this TextBox
will print all text pasted into it (no matter how) to the console instead of displaying it itself:
Class CapturePasteBox
Inherits TextBox
Protected Overrides Sub WndProc(ByRef m As Message)
If m.Msg = &H302 AndAlso Clipboard.ContainsText() Then
Dim text = Clipboard.GetText()
'' do something with text
Console.WriteLine(text)
Return '' return so the text won't be pasted into the TextBox
End If
MyBase.WndProc(m)
End Sub
End Class
In response to your comment:
The ComboBox
-control needs some special treatment, since
When sent to a combo box, the WM_PASTE message is handled by its edit control.
So you can use the following function/class using a NativeWindow
:
<System.Runtime.InteropServices.DllImport("user32.dll", SetLastError := True)> _
Private Shared Function FindWindowEx(hwndParent As IntPtr, hwndChildAfter As IntPtr, lpszClass As String, lpszWindow As String) As IntPtr
End Function
Public Class PasteHandler
Inherits NativeWindow
Protected Overrides Sub WndProc(ByRef m As Message)
If m.Msg = &H302 Then
Clipboard.SetText(ClipBoard.GetText().Replace("e", "XXX"))
End If
MyBase.WndProc(m)
End Sub
End Class
and use it with your ComboBox
:
'' Get the edit control of the combobox
Dim lhWnd As IntPtr = FindWindowEx(yourComboBox.Handle, IntPtr.Zero, "EDIT", Nothing)
'' assign the edit control to the Pastehandler
Dim p As New PasteHandler()
p.AssignHandle(lhWnd)
Upvotes: 2