//Declare this as public
const int MYKEYID1 = 9;
const int MYKEYID2 = 10;
const int MYKEYID3 = 11;
public const int VK_F2 = 0x71; //F2 key
public const int VK_F3 = 0x72; //F3 key
public const int VK_F4 = 0x73; //F4 key
//0x74,0x75...... etc for F5,F6 etc.....
public const int WM_HOTKEY = 0x312;
[DllImport("user32.dll")]
private static extern int RegisterHotKey(IntPtr hwnd, int id, int fsModifiers, int vk);
[DllImport("user32.dll")]
private static extern int UnregisterHotKey(IntPtr hwnd, int id);
protected override void WndProc(ref System.Windows.Forms.Message m)
{
try
{
if (m.Msg == WM_HOTKEY)
{
switch (m.WParam.ToInt32())
{
case MYKEYID1:
try
{
//do the action
}
catch (Exception ex)
{
}
break;
case MYKEYID2:
try
{
//do the action
}
catch (Exception ex)
{
}
break;
case MYKEYID3:
try
{
//do the action
}
catch (Exception ex)
{
}
break;
}
}
base.WndProc(ref m);
//Never Forget This
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//In form Load
try
{
RegisterHotKey(this.Handle, MYKEYID1, MOD_ALT, VK_F2); //Registers F2
RegisterHotKey(this.Handle, MYKEYID2, MOD_ALT, VK_F3); //Registers F3
RegisterHotKey(this.Handle, MYKEYID3, MOD_ALT, VK_F4); //Registers F4
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//In Form Closing==== Don't forget to do this
UnregisterHotKey(this.Handle, MYKEYID1);//Remember to unregister the hotkey
UnregisterHotKey(this.Handle, MYKEYID2); //Remember to unregister the hotkey
UnregisterHotKey(this.Handle, MYKEYID3); //Remember to unregister the hotkey
No comments:
Post a Comment