12

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!

The Mask
  • 17,007
  • 37
  • 111
  • 185
  • see [this](http://bloggablea.wordpress.com/2007/05/01/global-hotkeys-with-net/) – Shai Jan 18 '12 at 14:46
  • NOTE: your value for MOD_NOREPEAT is wrong. https://msdn.microsoft.com/en-us/library/windows/desktop/ms646309(v=vs.85).aspx – Drew Noakes Sep 24 '16 at 15:51
  • Your example works perfectly if you use the proper constant value for MOD_NOREPEAT and the right GetMessage() definition (which return an int and use MSG structure from System.Windows.Interop namespace) – tigrou Feb 11 '18 at 19:19

1 Answers1

2

This might help:

Hotkey in console app

Basically, you have to create a "hidden" form to make it work

Community
  • 1
  • 1
SLOBY
  • 1,007
  • 2
  • 10
  • 24