Re: Is it safe to post WM_COMMAND to the main window?
On Thu, 22 Feb 2007 22:16:52 -0500, "bob" <bob@domain.com> wrote:
I'd like to programmatically invoke a command that is 'normally' invoked by
a menu item. Let's say there is a menu item with command ID_FILE_OPEN.
When a user clicks on a the menu item a file dialog is displayed. I'd like
to invoke the same command programmatically (e.g. from one of CWinThreads
that my app creates). I think I could do that by simply posting a command
message with wparam set to ID_FILE_OPEN. Example:
AfxGetMainWnd()->PostMessage(WM_COMMAND, ID_FILE_OPEN). If I post the
message to the main window then - I think - command routing should properly
route it to the current view, doc, etc. - whatever has a proper handler for
the message. Am I correct? Are there any potential problems that I might
run into with this approach?
The routing will work, but there are a couple of other things to consider.
1. AfxGetMainWnd won't work from your thread, as least not without some
extra work that's better accomplished by passing the main window's HWND to
the thread as part of the thread's startup parameter data.
2. While MFC is smart enough to check for a disabled menu item instead of
blindly dispatching WM_COMMAND messages, I'm not sure if this covers items
that are temporarily disabled due to (say) the invocation of a modal
dialog. Unless you are somehow posting your messages only when your main
thread is in the proper receptive state, you should make sure you can't
post when the user is in the middle of something during which the sudden
appearance of the file selector dialog would be a major annoyance (or
worse).
--
Doug Harrison
Visual C++ MVP