I'm trying to register a hot key, I'm translating this C++ code into C#:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
[DllImport("user32.dll")]
public static extern
bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, int vk);
[DllImport("user32")]
public static extern
bool GetMessage(ref Message lpMsg, IntPtr handle, uint mMsgFilterInMain, uint mMsgFilterMax);
public const int MOD_ALT = 0x0001;
public const int MOD_CONTROL = 0x0002;
public const int MOD_SHIFT = 0x004;
public const int MOD_NOREPEAT = 0x400;
public const int WM_HOTKEY = 0x312;
public const int DSIX = 0x36;
static void Main(string[] args)
{
if (!RegisterHotKey(IntPtr.Zero, 1, MOD_ALT | MOD_NOREPEAT, DSIX))
{
Console.WriteLine("failed key register!");
}
Message msg = new Message();
while (!GetMessage(ref msg, IntPtr.Zero, 0, 0))
{
if (msg.message == WM_HOTKEY)
{
Console.WriteLine("do work..");
}
}
Console.ReadLine();
}
}
public class Message
{
public int message { get; set; }
}
}
but RegisterHotKey() never returns false.
I'm not sure about the arguments passed in the method, IntPtr.Zero should be null, and message class constructor's second argument requires an object. any help is very appreciated!
To register a hotkey use RegisterHotKey () function. It has 4 parameters: a handle to the window that will receive WM_HOTKEY messages, the identifier, key modifiers and virtual-key code of the hotkey. An application must specify an id value in the range 0x0000 through 0xBFFF.
This function cannot associate a hot key with a window created by another thread. RegisterHotKey fails if the keystrokes specified for the hot key have already been registered by another hot key. If a hot key already exists with the same hWnd and id parameters, it is maintained along with the new hot key.
The following example shows how to use the RegisterHotKey function with the MOD_NOREPEAT flag. In this example, the hotkey 'ALT+b' is registered for the main thread. When the hotkey is pressed, the thread will receive a WM_HOTKEY message, which will get picked up in the GetMessage call.
KeyModifier modifier = (KeyModifier)((int)m.LParam & 0xFFFF); // The modifier of the hotkey that was pressed. int id = m.WParam.ToInt32(); // The id of the hotkey that was pressed. MessageBox.Show("Hotkey has been pressed!"); UnregisterHotKey(this.Handle, 0); // Unregister hotkey with id 0 before closing the form.
This might help:
Hotkey in console app
Basically, you have to create a "hidden" form to make it work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With