我想知道如何通过鼠标点击捕获右键单击和粘贴选项。 这是一个winforms应用程序。我会在粘贴之前修改剪贴板的内容。 我可以通过ctrl + V执行此操作,但无法找到处理鼠标右键单击的方法。
到目前为止我已尝试过这个:
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
答案 0 :(得分:2)
您必须使用WndProc
处理WM_PASTE
窗口消息(可以找到所有消息的列表here)。
例如,这个TextBox
会将粘贴到其中的所有文本(无论如何)打印到控制台而不是自己显示:
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
回应你的评论:
ComboBox
- 控件需要一些special treatment,因为
当发送到组合框时,WM_PASTE消息由其编辑控件处理。
因此,您可以使用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
并将其与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)
答案 1 :(得分:0)
我发现这样做很棒:
<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