问题
I am a beginner in .net. This could be a silly question. I want to disable ctrl + c and ctrl + v keyboard shortcuts.
Before asking here I tried these codes link1 and link2 (not working)
private void dgvMain_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
this.dgvMain.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText;
}
private void dgvMain_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
this.dgvMain.ClipboardCopyMode = DataGridViewClipboardCopyMode.Disable;
}
and also
this.dgvMain.ClipboardCopyMode = DataGridViewClipboardCopyMode.Disable;
dgvMain
is datagridview
I maybe missing something here.
EDIT:
The properties for my datagridview which I have altered are:
AllowUserToResizeColumns -- False
AllowUserToResizeRows -- False
ClipboardCopyMode -- disable
ColumnsHeadersHeightSizeMode -- AutoSize
Dock -- Fill
ReadOnly -- True
TabStop -- False
Please help
Thanks in Advance.
回答1:
You don't spell out the not-working part, so I can only guess that you are referring to the TextBox part of the grid.
It should be enough to just have ClipboardCopyMode = Disable
but if the TextBox of the cell is in edit mode, that property gets ignored. You would have to disable the keys and the ContextMenu yourself:
Example:
public Form1()
{
InitializeComponent();
dgvMain.ClipboardCopyMode = DataGridViewClipboardCopyMode.Disable;
dgvMain.EditingControlShowing += dgvMain_EditingControlShowing;
}
void dgvMain_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
TextBox tb = e.Control as TextBox;
if (tb != null) {
tb.ContextMenuStrip = new ContextMenuStrip();
tb.KeyDown -= TextBox_KeyDown;
tb.KeyDown += TextBox_KeyDown;
}
}
void TextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && (e.KeyCode == Keys.C | e.KeyCode == Keys.V)) {
e.SuppressKeyPress = true;
}
}
回答2:
You can try this.
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
TextBox tb = e.Control as TextBox;
tb.ShortcutsEnabled = false;
}
来源:https://stackoverflow.com/questions/12780961/disable-copy-and-paste-in-datagridview