提问人:just_a_developer 提问时间:3/8/2022 更新时间:3/8/2022 访问量:127
如何防止 MenuStrip 处理 WinForms 中的某些键?
How to prevent MenuStrip from handling certain keys in WinForms?
问:
我有一个带有 MenuStrip 的表单,我想在其中对“CTRL + P”击键做出反应。
问题是,如果打开 MenuStrip,我的表单不会得到“CTRL + P”。
我尝试设置 Form 的 KeyPreview = true,并重写 ProcessCmdKey 但没有成功......
有我的 ProcessCmdKey 重写:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Control | Keys.P))
{
MessageBox.Show("ProcessCmdKey Control + P");
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
答:
1赞
Reza Aghaei
3/8/2022
#1
该消息不会经过窗体的关键事件,它将由每个下拉列表处理。
可以使用注释中提到的方法,或者作为另一个选项,可以实现 IMessageFilter 以在WM_KEYDOWN调度到下拉列表之前捕获它:
public partial class Form1 : Form, IMessageFilter
{
const int WM_KEYDOWN = 0x100;
public bool PreFilterMessage(ref Message m)
{
if (ActiveForm != this)
return false;
if (m.Msg == WM_KEYDOWN &&
(Keys)m.WParam == Keys.P && ModifierKeys == Keys.Control)
{
MessageBox.Show("Ctrl + P pressed");
return true;
}
return false;
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
Application.AddMessageFilter(this);
}
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
Application.RemoveMessageFilter(this);
}
}
评论
1赞
dr.null
3/8/2022
啊,大男孩,是的,我会用这个。
评论
Form
xStrip
KeyPress
KeyDown