I would like to know if this code can be adapted to use it inside a normal class (Example: Form1 Class) to don't need subclassing a Control.
Code is from BlueMonkMN
here Capture the option selected by the user in a windows default contextmenu?
Class MyTextBox : Inherits TextBox
Public Enum ContextCommands
WM_CUT = &H300
WM_COPY = &H301
WM_PASTE = &H302
End Enum
Public Class ContextCommandEventArgs
Inherits EventArgs
Public Property Command As ContextCommands
End Class
Event OnCut(sender As Object, e As ContextCommandEventArgs)
Event OnCopy(sender As Object, e As ContextCommandEventArgs)
Event OnPaste(sender As Object, e As ContextCommandEventArgs)
Protected Overrides Sub WndProc(ByRef m As Message)
MyBase.WndProc(m)
Select Case m.Msg
Case ContextCommands.WM_CUT
RaiseEvent OnCut(Me, New ContextCommandEventArgs() With {.Command = ContextCommands.WM_CUT})
Case ContextCommands.WM_COPY
RaiseEvent OnCopy(Me, New ContextCommandEventArgs() With {.Command = ContextCommands.WM_COPY})
Case ContextCommands.WM_PASTE
RaiseEvent OnPaste(Me, New ContextCommandEventArgs() With {.Command = ContextCommands.WM_PASTE})
End Select
End Sub
End Class
To understand better my problem, I'll show you what I've tried to adapt it:
Public Class Form1
Public Enum ContextCommands
WM_CUT = &H300
WM_COPY = &H301
WM_PASTE = &H302
End Enum
Public Class ContextCommandEventArgs
Inherits EventArgs
Public Property Command As ContextCommands
End Class
Event OnCut(TextBox1 As Object, e As ContextCommandEventArgs)
Event OnCopy(TextBox1 As Object, e As ContextCommandEventArgs)
Event OnPaste(TextBox1 As Object, e As ContextCommandEventArgs)
Protected Overrides Sub WndProc(ByRef m As Message)
MyBase.WndProc(m)
Select Case m.Msg
Case ContextCommands.WM_CUT
RaiseEvent OnCut(TextBox1, New ContextCommandEventArgs() With {.Command = ContextCommands.WM_CUT})
Case ContextCommands.WM_COPY
RaiseEvent OnCopy(TextBox1, New ContextCommandEventArgs() With {.Command = ContextCommands.WM_COPY})
Case ContextCommands.WM_PASTE
RaiseEvent OnPaste(TextBox1, New ContextCommandEventArgs() With {.Command = ContextCommands.WM_PASTE})
End Select
End Sub
Private Sub TextBox1_OnTextCommand() Handles TextBox1.TextChanged
If WM_CUT then...
Elseif WM_COPY then...
Elseif WM_Paste then...
End if
End Sub
Private Sub TextBox1_OnTextCommand() Handles Me.OnPaste, Me.OnCopy, Me.OnCut
MsgBox("Activated")
End Sub
End Class
This is not a simple task for a VB developer, but I hope this helps. The code no longer relates to a specific textbox, but you should be able to identify which textbox caused the event by comparing
cwp.hWnd
withTextBox.Handle
values if you need to.EditMenuHook.Enable
should probably only be called once at the beginning of your application to turn on the hook, and once at the end to turn it off.