You can probably implement IMessageFilter and handle the Keys combinations you want.
You then have to use Application.AddMessageFilter() to add the message filter and Application.RemoveMessageFilter() to remove it when not needed anymore.
Here, the UserControl's DesignMode property is checked, so the filter is added at run.time only.
Possibly, add a public Property that can add / remove / change combinations of Keys, in case there's a conflict with other controls.
The GetAncestor() function is used to determine whether the Form where the Keys combination is triggered is the Parent Form of this instance of the UserControl.
PreFilterMessage() is called when messages are generated in any Form of the application.
If you instead want to perform an action in any case, even when the combination is generated in another open Form (and, maybe, pop the Parent Form in front), just remove that check.
Filter Control + F.
If you need more filters, as mentioned, use a collection to handle these combinations.
当接收到WM_KEYDOWN 时,WParam
包含虚拟键码。Virtual Key 值等效于Keys枚举器。
在ModifierKeys属性包含相关按键当前活动(在Control单独密钥在这里测试,当然你也可以添加其他的快捷键使用,如CTRL+SHIFT)。
using System.ComponentModel;
using System.Runtime.InteropServices;
public partial class SomeUserControl : UserControl, IMessageFilter
{
public SomeUserControl() => InitializeComponent();
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == WM_KEYDOWN) {
if (GetAncestor(m.HWnd, 2).Equals(ParentForm.Handle)) {
if (m.WParam.ToInt32() == (int)Keys.F && ModifierKeys == Keys.Control) {
someChildTextBox.Focus();
}
}
}
return false;
}
protected override void OnHandleCreated(EventArgs e) {
base.OnHandleCreated(e);
if (!DesignMode) Application.AddMessageFilter(this);
}
protected override void OnHandleDestroyed(EventArgs e) {
if (!DesignMode) Application.RemoveMessageFilter(this);
base.OnHandleDestroyed(e);
}
private const int WM_KEYDOWN = 0x0100;
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr GetAncestor(IntPtr hWnd, uint flags);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句