It's been like an hour. I just want to implement Copy & Paste while editing my DataGridView. Maybe I'm asking too much?
This is what I have so far. Initalization:
dataGridView.EditingControlShowing = new DataGridViewEditingControlShowingEventHandler(dataGridView_EditingControlShowing);
I guess which calls:
private void dataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyDown = Control_KeyDown;
}
And we have:
private void Control_KeyDown(object sender, KeyEventArgs e)
{
if (e.Modifiers == Keys.Control && e.KeyCode == Keys.C)
{
System.Diagnostics.Debug.WriteLine("control c");
}
}
I can capture Control. I can capture C. I can't capture Ctrl-C. It's impossible.
CodePudding user response:
The KeyDown
event is only triggered when a cell is in edit mode in the DataGridView
, so the keyboard shortcut event catcher will not work in other cases. You can fix this problem by pointing the KeyDown
event handler as follows:
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is DataGridViewTextBoxEditingControl)
{
DataGridViewTextBoxEditingControl tb = e.Control as DataGridViewTextBoxEditingControl;
tb.KeyDown -= dataGridView_KeyDown;
tb.PreviewKeyDown -= Control_KeyDown;
tb.KeyDown = dataGridView_KeyDown;
tb.PreviewKeyDown = Control_KeyDown;
}
}
private void Control_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == (Keys.Control | Keys.C))
{
System.Diagnostics.Debug.WriteLine("control c");
}
}
A similar discussion is available in this post.
CodePudding user response:
The grids PreviewKeyDown
event should fire when a cell is not in edit mode… something like…
private void dataGridView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) {
if (e.Modifiers == Keys.Control && e.KeyCode == Keys.C) {
System.Diagnostics.Debug.WriteLine("Preview control c");
}
}