繁体   English   中英

C#Keys.Apps将始终打开Windows上下文菜单

[英]C# Keys.Apps will always open Windows 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

截图

有任何想法吗?

由于ProcessCmdKey()PreviewKeyDown()没有完成这项工作,因此我决定采用另一种方法...

我发现了(至少出于我的需要)一个解决问题的不错的解决方法。 在表单的“设计器”部分,我为我的TextBox定义了一个新的ContextMenuStrip:

// editSearchField
[...]
this.editSearchField.ContextMenuStrip = new System.Windows.Forms.ContextMenuStrip();

这导致Windows默认上下文菜单不再显示。 由于ContextMenuStrip没有ToolStripMenuItems,因此将立即丢弃它。

为了完整KeyDown() ,这是我更改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;
  }
}

编辑:修复了代码中的错误

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM