Using VS2010 framework 4 VB.net. I have a text box and a datagridview control on a form. I need to trap a CR (enter key press) in the following cases:
1) When the cursor is in a cell on the datagridview.
2) When the cursor is in a text box.
3) When the cursor(focus) is on the form.
The real basis of the issue is the need to override the datagridview's CR behavior as natively it both swallows the CR(making it difficult to trap) and it moves the cursor to the cell below(when the enter key is pressed). I have had some success when using some code posted here which traps all instances of a CR:
Detecting Enter keypress on VB.NET
Here is the accepted solution from the above post with a debug.print addition:
Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, _
ByVal keyData As System.Windows.Forms.Keys) _
As Boolean
If msg.WParam.ToInt32() = CInt(Keys.Enter) Then
'deal with enter key presses here......
Debug.Print("Active: " & ActiveControl.Name.ToString & " " & Len(ActiveControl.Name.ToString))
Return True
End If
Return MyBase.ProcessCmdKey(msg, keyData)
End Function
The above solution traps ALL key presses on the form even when they come from a text box, the form itself or the datagridview control. But I need to determine the control from which the CR originated. I see that HWnd is passed in the ProcessCmdKey function(msg.HWnd), but the values it returns do not seem to correspond to the .handle value of any of the originating controls (textbox1.handle or the me.handle or the datagridview1.handle). Upon further reading it appears that this is not a valid comparison.
I have also tried to use the activecontrol.name method to obtain the currently active control and deduce which control sent the CR. However, even with the cursor planted in a cell in the datagridview and sending CRs from the cell, activecontrol.name returns a zero length string. It does however return the name of the text box when I enter a CR from the text box.
How can I determine which control sent the msg?
Much Thanks!