1

I have an application in which the worker thread needs to call a method on main thread. I am planning to send a custom message via win32api.PostThreadMessage(with message WM_USER+X), and when this message is received, some function must get executed on main thread. What I am looking is, to register a method to the corresponding WM_USER_X message?

AbhishekD
  • 66
  • 7
  • 1
    That's not how things work. You don't register methods to messages. If you post a message to a thread, then you need to modify the main application's message loop (and any modal message loops that run). Really a very bad idea to post directly to main thread. Better is to post to a window. Then you need to handle the message in that window's window procedure. – David Heffernan Nov 22 '17 at 12:32
  • 2
    See also ["Why do messages posted by PostThreadMessage disappear?"](https://blogs.msdn.microsoft.com/oldnewthing/20090930-00/?p=16553). The idiomatic way is to pass a window handle from the main thread to the worker thread. Then the worker thread does a regular `PostMessage()` specifying this window handle. – zett42 Nov 22 '17 at 12:40
  • @DavidHeffernan, I saw how to create a window with custom messages and handle those via https://www.programcreek.com/python/example/53218/win32con.WM_USER, where we create a message map (Ref example 2) But what if I don't want to create a window, can it be done? – AbhishekD Nov 22 '17 at 12:59
  • 1
    Create an invisible, [message-only window](https://msdn.microsoft.com/en-us/library/windows/desktop/ms632599(v=vs.85).aspx#message_only). – zett42 Nov 22 '17 at 13:02
  • 1
    You do want to create a window. A message only window. That way you can be sure that your message will be handled. Otherwise you fall foul of the problems that @zett42 and I describe. I don't understand why you ask how to do something having such pre-determined beliefs as to what the right solution is. – David Heffernan Nov 22 '17 at 13:02
  • Instead of `WM_USER+...` I'd rather use `WM_APP+...`. See this: https://stackoverflow.com/questions/30843497/wm-user-vs-wm-app – Jabberwocky Nov 22 '17 at 17:24

1 Answers1

-1

Look at the RegisterWindowMessage function, it does pretty much exactly what you are after (provides a message number that should not collide with any other). The one downside is that the message number is then not a constant but will vary from run to run of your program, this makes the message loop somewhat more complicated but is well worth it for this sort of thing.

SoronelHaetir
  • 14,104
  • 1
  • 12
  • 23