-2

I need to break the message loop in win32 keyboard hook. The loop look like this,

MSG msg;
    while (GetMessage(&msg, NULL, NULL, NULL))  
    {
        TranslateMessage(&msg); 
        DispatchMessage(&msg);
    }

I used unhook method but it doesn't work. and I have another Question that if I change while loop parameter to !GetMessage it work same as before. and if I add printf inside that while loop its not printing anything. I just want to make a dll for keyboard hook. and method in dll need to end. with this(message loop) I cant end(or return something) that method.

Sorry for my bad English.

Thanks.

getek mer
  • 113
  • 2
  • 5
  • 1
    @ÖöTiib In fact, this loop cannot ever return -1, see a great many prior discussions – David Heffernan Nov 30 '18 at 13:39
  • 1
    If you need to break the loop based on external state, use an even, `MsgWaitForMultipleEvents`, and set the event from the hook procedure as appropriate. @ÖöTiib: This call to `GetMessage` cannot fail. It is passing a clearly visible valid pointer, and doesn't apply any filters. – IInspectable Nov 30 '18 at 13:41
  • @getek : you have to catch the WM_ Message for Keypress ( I don' know if it is the intent). and create/ call a function. – Blood-HaZaRd Nov 30 '18 at 13:41
  • Correction, that should read *"event"* and `MsgWaitForMultipleObjects`. – IInspectable Nov 30 '18 at 13:48
  • Pumping a message loop in a DLL can break a lot of things. The only real way to make that work is running this code on a separate thread. You could create that thread in DllMain(). But, "don't do that" is the only really good advice. – Hans Passant Nov 30 '18 at 13:51
  • This sound like an XY Problem. **What are you really trying to do?** – selbie Nov 30 '18 at 15:12
  • I have a c# application. I need a global hotkey without form but I cant do this in c#. so i decide to use a c++ dll. but I cant understand how i can create a library with infinite loop. – getek mer Nov 30 '18 at 15:24
  • If you want a global hotkey, use [RegisterHotKey](https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-registerhotkey). Create a [message-only window](https://learn.microsoft.com/en-us/windows/desktop/winmsg/window-features#message-only-windows) for the message callbacks if your application doesn't have a GUI you can repurpose as a message receiver. – IInspectable Nov 30 '18 at 17:00
  • @ÖöTiib see [When will GetMessage return -1?](https://blogs.msdn.microsoft.com/oldnewthing/20130322-00/?p=4873) – Remy Lebeau Dec 01 '18 at 01:19

1 Answers1

1

Use a PostQuitMessage(0) to break the prodecure. You can put it in your window procedure, for example, in the WM_DESTROY message comes.

Arush Agarampur
  • 1,340
  • 7
  • 20