views:

24

answers:

2

In a VB.NET Winforms application, I have a form that contains both a datagridview and a textbox. I have some menu item entries that have shortcuts of Ctrl-X, Ctrl-C, and Ctrl-V that operate on the datagridview. However, these override the default cut, copy, and paste shortcuts for the textbox. How can I make the menu shortcuts only apply when the datagridview has focus?

+2  A: 

In the DataGridView.GotFocus event, assign the shortcuts and in the LostFocus event remove them again.

So something like this:

Private Sub DataGridView_GotFocus(sender as Object, e as EventArgs) Handles DataGridView.GotFocus
  menuItem1.Shortcut = Shortcut.CtrlV
End sub

Private Sub DataGridView_LostFocus(sender as Object, e as EventArgs) Handles DataGridView.LostFocus
  menuItem1.Shortcut = Shortcut.None
End sub

Generally though, I would not assign other functions to the Ctrl-X, Ctrl-C, and Ctrl-V keys.

Peladao
+1  A: 

Proper UI design requires disabling the menu item when it isn't functional. A side-effect is that it will no longer steal the keystroke, just what you want. The Application.Idle event is handy for that.

Public Class Form1
    Public Sub New()
        InitializeComponent()
        AddHandler Application.Idle, Application_Idle
    End Sub
    Private Sub Application_Idle(ByVal sender As Object, ByVal e As EventArgs)
        CopyToolStripMenuItem.Enabled = DataGridView1.Focus
        '' etc...
    End Sub
End Class
Hans Passant