How to hook up CNTL-x/c/v keypress events for cut/copy/paste routines
(This should be an easy one... but Googling for it is a mess of rabbit trails.)
I have a Windows Forms app, with a TabControl. On the first tab (which is a bunch of textboxes), the CNTL-x/c/v keyboard shortcuts for cut/copy/paste work as expected. On the second tab (which is a DataGridView), the keyboard shortcuts don't do anything.
How do I hook up these key开发者_开发知识库press events to my cut/copy/paste routines?
Please note: I already have great cut/copy/paste routines for my DataGridView--and they work fine when launched from the tooltip buttons or menus. I just need to hook up those subs to the CNTL-x/c/v keypress events.
You should already have one or more of the following events for your control: KeyPress
, KeyUp
, and KeyDown
.
Handle those events like you would any other. In your event handler you can do a check against the arguement provided to see if any control keys are/were pressed and which other keys have been pressed as well.
If the correct combination of keys have been pressed you can add things to the clipboard or attempt to copy from the clipboard to your control.
From Matthew's tip, I was able to put together the following working code ('DGVCutCopyPaste' is, of course, my class for cutting/copying/pasting multiple cells in a DataGridView--not a built-in):
Private Sub DataGridView1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) _
Handles DataGridView1.KeyUp
If Control.ModifierKeys = Keys.Control Then
Select Case e.KeyCode
Case Keys.X
DGVCutCopyPaste.CutDGVCells(DataGridView1)
Case Keys.C
DGVCutCopyPaste.CopyDGVCells(DataGridView1)
Case Keys.V
If Clipboard.ContainsText Then
DGVCutCopyPaste.PasteDGVCells(DataGridView1)
End If
End Select
End If
End Sub
I had some trouble with the "KeyPress" event (which has a different signature), but the "KeyUp" and "KeyDown" work fine this way.
精彩评论