我正在尝试处理键盘上的Apps / Context Menu键。键应该在TextBox中捕获,然后应该显示DataGridView对象的编程的ContextMenuStrip。
然而,显示ContextMenuStrip非常简单。我唯一的问题是标志e.Handled = true
似乎无法阻止TextBox的Windows默认上下文菜单出现。因此,它为DataGridView 打开ContextMenuStrip,为TextBox打开默认上下文菜单。
以下代码适用:
void EditSearchField_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Apps)
{
// ContextMenuStrip is shown here
DataGridView1.ContextMenuStrip.Show(DataGridView1, new Point(0, 0));
e.Handled = true;
e.SuppressKeyPress = true;
}
}
结果看起来很不愉快。 KeyPreview = true
也已设置。
有什么想法吗?
答案 0 :(得分:2)
由于ProcessCmdKey()
和PreviewKeyDown()
没有完成这项工作,我决定采取另一种方法......
我找到了一个(至少对我而言)我的问题的正确解决方法。在"设计师"我的表单的一部分我为我的TextBox定义了一个新的ContextMenuStrip:
// editSearchField
[...]
this.editSearchField.ContextMenuStrip = new System.Windows.Forms.ContextMenuStrip();
这导致Windows默认上下文菜单不再显示。由于ContextMenuStrip没有ToolStripMenuItems,因此会立即将其丢弃。
为了完整起见,我在此处更改了KeyDown()
功能
void EditSearchField_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Apps)
{
if (dgvClients.SelectedRows.Count > 0)
{
// force the selected row to be visible, or else we could get a .NET debugger
dgvClients.CurrentCell = dgvClients.SelectedRows[0].Cells[0];
// prepare context menu (disable inaccessible entries)
Point ptMouse = dgvClients.GetCellDisplayRectangle(0, dgvClients.SelectedRows[0].Index, false).Location;
var mouseEvtArgs = new MouseEventArgs(MouseButtons.Right, 1, 0, 0, 0);
var mouseDgvArgs = new DataGridViewCellMouseEventArgs(0, dgvClients.SelectedRows[0].Index, ptMouse.X, ptMouse.Y, mouseEvtArgs);
DgvClientsMouseDown(dgvClients, mouseDgvArgs);
// calculate location for the context menu and finally show it
Point ptContextMenuPos = dgvClients.PointToScreen(ptMouse);
ptContextMenuPos.X += dgvClients.Width / 2;
ptContextMenuPos.Y += dgvClients.RowTemplate.Height / 2;
dgvClients.ContextMenuStrip.Show(ptContextMenuPos);
}
e.Handled = true;
e.SuppressKeyPress = true;
}
}
编辑修复了代码中的错误