Reputation: 59
To catch the hot key Ctrl+A
, we can use following statement in Form1_KeyDown
.
if (e.Modifiers == Keys.Control && e.KeyCode == Keys.A)
{
MessageBox.Show("Test");
}
To catch Ctrl+Alt+A
, we can use:
if (e.Control && e.Alt)
{
if (e.KeyCode == Keys.A)
{
// Your code goes here
}
}
The question is how to catch the hot key like Ctrl+A+B
?
Upvotes: 2
Views: 177
Reputation: 39122
Here's something to get you started using IMessageFilter.
This will trigger when Ctrl-A-B is pressed DOWN, not on release. It also currently will repeatedly trigger while those keys are held down. This could be changed with another boolean variable in the mix. This is definitely not perfect...
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private MyFilter mf = new MyFilter();
private void Form1_Load(object sender, EventArgs e)
{
mf.Ctrl_A_B += Mf_Ctrl_A_B;
Application.AddMessageFilter(mf);
}
private void Mf_Ctrl_A_B()
{
Console.WriteLine("Ctrl-A-B was held down!");
}
}
public class MyFilter : IMessageFilter
{
private bool keyCtrl;
private bool keyA;
private bool keyB;
private const int WM_KEYDOWN = 0x100;
private const int WM_KEYUP = 0x101;
public delegate void dlg_Ctrl_A_B();
public event dlg_Ctrl_A_B Ctrl_A_B;
public bool PreFilterMessage(ref Message m)
{
Keys keyData;
switch (m.Msg)
{
case WM_KEYDOWN:
keyData = (Keys)((int)m.WParam);
switch (keyData)
{
case Keys.ControlKey:
keyCtrl = true;
break;
case Keys.A:
keyA = true;
break;
case Keys.B:
keyB = true;
break;
}
if (keyCtrl && keyA && keyB)
{
Ctrl_A_B?.Invoke();
}
break;
case WM_KEYUP:
keyData = (Keys)((int)m.WParam);
switch (keyData)
{
case Keys.ControlKey:
keyCtrl = false;
break;
case Keys.A:
keyA = false;
break;
case Keys.B:
keyB = false;
break;
}
break;
}
return false;
}
}
Upvotes: 1
Reputation: 4660
You can consider the first key as an additional or a custom modifier to expand the range of the shortcuts.
Declare a class variable to hold that modifier:
private Keys KeyModifier = Keys.None;
Handle the KeyDown
event as follows:
private void FormWhatEver_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control)
{
switch (e.KeyCode)
{
case Keys.B:
if (KeyModifier == Keys.A)
{
// Handle Ctrl+AB
}
else
{
// Handle Ctrl+B
}
break;
case Keys.C:
if (KeyModifier == Keys.A)
{
// Handle Ctrl+AC
}
else
{
// Handle Ctrl+C
}
break;
default:
// Otherwise set the pressed key as a key modifier.
KeyModifier = e.KeyCode;
break;
}
}
}
Reset the modifier when the Control
key is released. This is important in order to make the above work correctly.
private void FormWhatEver_KeyUp(object sender, KeyEventArgs e)
{
if (!e.Control) KeyModifier = Keys.None;
}
Upvotes: 0