I have a custom class derived from CWnd that I would like to post a message to from a worker thread. I am using the PostMessage function to achieve this. The first argument to PostMessage is the HWND type handle to my class, and the next is the message I would like handled. For the first parameter, I generate the handle to my class using GetSafeHwnd() function, and for the second parameter, I use WM_USER+3. Also, I declare a message map inside my class header file, and add an entry for the message handler inside the BEGIN_MESSAGE_MAP and END_MESSAGE_MAP block. However, my handler is not getting called. I have also checked the return value of PostMessage function, it is 1, that means success.
Here is my code :
Inside MyClass.h
class CMyClass : CWnd
{
....
....
public:
void InitHandle();
protected:
afx_msg LRESULT OnMessageReceived(WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()
}
Inside MyClass.cpp
#define WM_MY_MESSAGE WM_USER+3
HWND handleToMyClassWindow;
BEGIN_MESSAGE_MAP(CMyClass, CWnd)
ON_MESSAGE(WM_MY_MESSAGE, OnMessageReceived)
END_MESSAGE_MAP()
LRESULT CMyClass::OnMessageReceived(WPARAM wParam, LPARAM lParam)
{ .... }
void CMyClass::InitHandle()
{
handleToMyClassWindow = GetSafeHwnd();
}
Inside Worker thread
UINT WorkerThreadFunction(LPVOID pParam )
{
....
PostMessage(handleToMyClassWindow, WM_MY_MESSAGE, NULL, NULL);
....
}
My question is, what are the possible reasons for the OnMessageReceived handler to not be called.
P.S.
I take care that the calling object calls the InitHandle() function.
I tried the same technique with the View class (derived from CView) of my program, and it works there, but fails here.
You cannot post to a window if it has not been created. GetSafeHwnd() will return NULL if you have not actually created a window using your class.
Related
The general rule of thumb is not to call a virtual function from a constructor because it can lead to unpredictable behavior. So why does it work sometimes?
I recently wrote a couple of base classes with pure virtual functions, and accidentally included an indirect call to those functions in the constructor. I realized my mistake and corrected it, but one of them worked while the other did not.
Here's the definition of the class that worked:
template <typename TWindow>
class dialog_base
{
static INT_PTR CALLBACK dlg_proc_internal
(HWND,
UINT,
WPARAM,
LPARAM);
protected:
dialog_base
(const LPCWSTR templateName,
const HWND parent)
{
CREATESTRUCT create;
create.lpCreateParams = this;
m_hwnd = CreateDialogParam(
hinstance_, templateName, parent, dlg_proc_internal,
reinterpret_cast<LPARAM>(&create));
}
HWND m_hwnd;
virtual INT_PTR CALLBACK dlg_proc
(UINT,
WPARAM,
LPARAM) = 0;
public:
virtual ~dialog_base()
{
DestroyWindow(m_hwnd);
}
HWND GetHandle() const;
void show() const;
};
In this class, the DialogBoxParam function calls dlg_proc_internal, passing the WM_NCCREATE message:
template <typename TWindow>
INT_PTR dialog_base<TWindow>::dlg_proc_internal
(HWND hWnd,
UINT msg,
WPARAM wParam,
LPARAM lParam)
{
dialog_base<TWindow>* pThis;
if (msg == WM_NCCREATE)
{
pThis = static_cast<dialog_base<TWindow>*>(reinterpret_cast<
CREATESTRUCT*>(lParam)->lpCreateParams);
SetLastError(0);
if (!SetWindowLongPtr(
hWnd, GWLP_USERDATA,
reinterpret_cast<LONG_PTR>(pThis)) && GetLastError() != 0)
return 0;
}
else
{
pThis = reinterpret_cast<dialog_base<TWindow>*>(
GetWindowLongPtr(hWnd, GWLP_USERDATA));
}
return pThis
? pThis->dlg_proc(msg, wParam, lParam)
: DefWindowProc(hWnd, msg, wParam, lParam);
}
This function retrieves the pointer passed as the last argument to CreateDialogParam and stores it in the window so that it can be retrieved again in later calls to the function.
It then mistakenly calls the pure virtual function dlg_proc instead of returning -- and appears to work just fine through the constructor of a child class.
I created a different class which was almost identical, except that it called CreateWindowEx instead of CreateDialogParam. The pointer argument was passed in much the same way, and used to call the pure virtual function. This time, it failed as one might expect. So what's the difference between the two situations?
EDIT:
Perhaps I should clarify. I'm not asking "Why can't I call virtual members from a constructor?". I'm asking about why the process of resolving virtual members before the object is constructed can sometimes create situations in which an error does not occur, and the correct function is called.
Calling a virtual function from a constructor has perfectly predictable behavior in C++, just like it has perfectly predictable behavior in .Net and Java. However, it's not the same behavior.
In C++, virtual functions dispatch on the type of the object at the moment of calling. Some other languages will use the intended type of object. Both are viable choices, both have risks, but since this is a C++ question I'll focus on the C++ risk.
In C++, virtual functions can be pure virtual. dlg_proc in the question is such a pure virtual function. These are declared in the base class, but not (necessarily) defined there. Trying to call a function that you did not define is Undefined Behavior. Compilers are entirely free to do whatever they like.
One possible implementation is that a compiler just calls a random other function. This could be remove(filename). It might also be the override from a derived class. But there are a million other possible results, including crashes and hangs. So we don't try to predict what happens, and just say: don't call pure virtual functions from ctors.
Footnote:
You can actually provide a body for a pure virtual function; the language allows it.
CreateDialog...() (and DialogBox...()) does not pass its dwInitParam parameter value to your message procedure via WM_(NC)CREATE. It is passed via WM_INITDIALOG instead, which you are not handling. Only CreateWindow/Ex() passes its lpParam parameter values to the message procedure via WM_(NC)CREATE. This is documented behavior!
But more importantly, you are manually passing a CREATESTRUCT to CreateDialogParam(). That is not necessary, especially since you are not handling that extra CREATESTRUCT in your WM_NCCREATE handler. When the system issues WM_(NC)CREATE to a window, the lParam passed to CreateWindow/Ex() gets wrapped in a system-provided CREATESTRUCT. So, even if CreateDialogParam() were to pass its dwInitParam as the lParam to CreateWindowEx() (which is not documented behavior, BTW), you still wouldn't be obtaining your dialog_base* pointer correctly inside your message procedure, as you are not handling that 2 separate CREATESTRUCTs could be present. So, your code has undefined behavior when using the pThis pointer for any reason, since you are not passing that pointer value into your message procedure correctly.
You need to pass your this pointer directly to CreateDialogParam() without wrapping it, and you need to handle WM_INITDIALOG instead of WM_NCCREATE. Then your virtual method should behave as expected (ie, it will not dispatch to a derived class, since WM_INITDIALOG is being handled within the context of the base class constructor).
Also, DO NOT call DefWindowProc() in your message procedure (or derived overrides) when using CreateDialog...() (or DialogBox...()). This is specifically stated in the DialogProc documentation:
Although the dialog box procedure is similar to a window procedure, it must not call the DefWindowProc function to process unwanted messages. Unwanted messages are processed internally by the dialog box window procedure.
Try this instead:
template <typename TWindow>
class dialog_base
{
static INT_PTR CALLBACK dlg_proc_internal(HWND, UINT, WPARAM, LPARAM);
protected:
dialog_base(LPCWSTR templateName, HWND parent)
{
m_hwnd = CreateDialogParamW(hinstance_, templateName, parent, dlg_proc_internal, reinterpret_cast<LPARAM>(this));
}
HWND m_hwnd;
virtual INT_PTR CALLBACK dlg_proc(UINT, WPARAM, LPARAM) = 0;
public:
virtual ~dialog_base()
{
DestroyWindow(m_hwnd);
}
HWND GetHandle() const;
void show() const;
};
template <typename TWindow>
INT_PTR dialog_base<TWindow>::dlg_proc_internal (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
dialog_base<TWindow>* pThis;
if (msg == WM_INITDIALOG)
{
pThis = reinterpret_cast<dialog_base<TWindow>*>(lParam);
// you CANT cancel dialog creation here when
// using CreateDialog...(), only when using
// DialogBox...()! So, no point in doing any
// error checking on SetWindowLongPtr()...
SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pThis));
// no point in trying to call pThis->dlg_proc()
// here since it won't be dispatched to derived
// classes anyway...
return TRUE; // or FALSE, depending on your needs...
}
pThis = reinterpret_cast<dialog_base<TWindow>*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
if (!pThis) return FALSE;
return pThis->dlg_proc(msg, wParam, lParam);
}
Though I've had plenty of software experience I've not done a great deal of Windows programming. I'm trying to post a WM_USER message from a thread so that it gets picked up in the main UI thread but I'm having some trouble. This is in C++ using VS2010 and MFC.
I've created a message map thus,
#define WM_MYMSG (WM_USER + 77)
BEGIN_MESSAGE_MAP(CMyApp, CWinApp)
ON_MESSAGE(WM_MYMSG, DoSomething)
END_MESSAGE_MAP()
Declared the handler function as follows,
afx_msg LRESULT DoSomething(WPARAM wParam, LPARAM lParam);
And written the function body as,
LRESULT CMyApp::DoSomething( WPARAM wParam, LPARAM lParam )
{
UNREFERENCED_PARAMETER(wParam);
UNREFERENCED_PARAMETER(lParam);
CallSomeFunction();
return 0L;
}
As far as I can see this is all in line with what MSDN says as stated here.
http://msdn.microsoft.com/en-gb/library/k35k2bfs(v=vs.100).aspx
However I'm getting an
error C2440: 'static_cast' : cannot convert from 'LRESULT (__cdecl CMyApp::*)(WPARAM,LPARAM)' to 'LRESULT (__cdecl CWnd::* )(WPARAM,LPARAM)'
relating to the line
ON_MESSAGE(WM_AVATAR_SCALE_MSG, DoSomething)
Can anyone let me know what the problem is?
Thanks for reading.
Paul
CMyApp inherits from CWinApp, which inherits from CWinThread. CWinThread user-defined messages take a special macro in their message map for what you want to do:
Change this:
ON_MESSAGE(WM_AVATAR_SCALE_MSG, DoSomething)
To this:
ON_THREAD_MESSAGE(WM_AVATAR_SCALE_MSG, DoSomething)
Assuming DoSomething() is a member of your CMyApp class.
See the documentation on ON_THREAD_MESSAGE() for more information.
THe problem is that the message map expects a function on a CWnd, whereas your class clearly is not a CWnd, either by virtue of actually being such or inheriting from CWnd.
The function expects you to pass a method of CWnd that takes a WPARAM and an LPARAM, but you're passing in a function of CMyApp.
Make the CMyApp class extend off of the CWnd class:
class CMyApp : public CWnd {
// members here
};
edit
If this isn't possible, then you're going to have to find a way to pass in a function of CWnd or any other function of a class that extends off of CWnd with the right parameters and return type.
I have asked two questions earlier about this and for each post there was some solutions i tried them, but the problem still exist.
My first question was : why a windowless Activex does not return the Handle. the suggestion was "change the creation setting an make windowless activate off, i have tried it but still m_hWnd property has returned zero as GetSafeHwnd() method has did.
the second one was the same question this one focused on COleControl class and it's ancestor CWnd. the solution was as this "Create invisible window somewhere in your control initialization code. Handle the messages sent to this window, and call controls methods directly". so i did that but the created class still returns zero handle.
here is my new invisible class source:
// moWind.cpp : implementation file
//
#include "stdafx.h"
#include "PINActive.h"
#include "moWind.h"
#include "include\xfspin.h"
#include <math.h>
// moWind
IMPLEMENT_DYNAMIC(moWind, CWnd)
moWind::moWind(){}
moWind::~moWind(){}
//=============================================================
LRESULT moWind::OnExecuteEvent (WPARAM wParam, LPARAM lParam)
{
WFSRESULT *pResult = (WFSRESULT *)lParam;
CString EK=_T("");
CString str;
int reskey=0;
if (pResult->u.dwEventID=WFS_EXEE_PIN_KEY)
{
LPWFSPINKEY pressedkey;
pressedkey=(LPWFSPINKEY)pResult->lpBuffer;
reskey = log10((double)pressedkey->ulDigit) / log10((double)2);
EK.Format("%d",reskey);
xfsOnKeyEvent->OnKeyRecieved(reskey);
}
else
{
str.Format("ExecuteEvent: ID = %d\r\n", pResult->u.dwEventID);
}
MessageBox("a Execute message Recieved");
return 0;
}
BEGIN_MESSAGE_MAP(moWind, CWnd)
ON_MESSAGE(WFS_EXECUTE_EVENT,OnExecuteEvent)
END_MESSAGE_MAP()
and this is .h file of the class:
// moWind.h
class IXFSEvents
{
protected:
IXFSEvents(){};
virtual ~IXFSEvents(){};
public:
virtual void OnKeyRecieved(int key)=0;
};
class moWind : public CWnd
{
DECLARE_DYNAMIC(moWind)
public:
moWind();
virtual ~moWind();
void Register(IXFSEvents* obj)
{
xfsOnKeyEvent= obj;
}
protected:
IXFSEvents* xfsOnKeyEvent;
LRESULT OnExecuteEvent (WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()
};
and at the end here this the way I've used this class in my Activex:
in the myActivex.h file:
include "moWind.h"
class CmyActivexCtrl : public COleControl, public IXFSEvents
{
...
Class definition
...
protected:
moWind tmpWind;
.
.
};
finally in the creation method of myActivex i have initialized the component callback method an wanted to get it's Handle as this:
CmyActivexCtrl::CmyActivexCtrl()
{
InitializeIIDs(&IID_DmyActivex, &IID_DmyActivexEvents);
tmpWind.Register(this);
myOtherComponent.WindowsHandle=tmpWind.GetSafeHwnd(); //here my Cwnd derived class returns zero
//my other component gets the handle and call an API with it to register
//the given handle and force the API to send the messages to that handle.
}
As you mentioned you need a window handle to be able to receive user messages through it, you always have an option of creating a helper window, such as message only window, see Using CreateWindowEx to Make a Message-Only Window.
For your windowless control it is okay to not have any window handle at all, so you cannot really rely on handle availability unless you own a window yourself.
So I'm writing some wrapper classes for GUI programming in Win32. I'm starting with a Window class, and so far it contains a MainLoop method that is basically a clone of the standard Win32 WinMain function. That way, one can do something like this:
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int nCmdShow) {
Window *win = new Window();
// Do all your widget creation and add it to the window object...
return win->MainLoop(hInst, hPrev, szCmdLine, nCmdShow);
}
Inside the window object's MainLoop method, it must create the new Win32 window by setting its lpfnWndProc member. This member, as any Win32 programmer knows, is a function pointer to a specifically defined WndProc function. The problem is, if I were to create a WndProc function, I would need access to that window object's members (so that it knew what to draw on the window, etc.). This leaves me two options (that I know of):
I can define WndProc at the top level, but that cuts off access to the object's members.
I can define it as a class method, but then it's not the exact function type that lpfnWndProc asks for, so I can't set it!
Can anyone help me unravel this catch-22?
You could also make it a static member function. :)
Anyways, a solution depends on if you need only one window or if you need multiple windows.
First a solution for single windows:
// in .h
class Window{
public:
static LRESULT WINAPI MessageProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT InternalMessageProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
// ...
};
// in .cpp
#include "Window.h"
Window* global_window = 0;
Window::Window(/*...*/){
if(!global_window)
global_window = this;
else
// error or exception... or something else
}
LRESULT WINAPI Window::MessageProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam){
return global_window->InternalMessageProc(hWnd, msg, wParam, lParam);
}
Now if you want to allow multiple windows, use a std::map (or if your compiler supports std::unordered_map).
Edit: This solution comes with some subtle problems. As #Ben Voigt points out in his comment, you get a chicken and egg problem as the MessageProc is called inside of CreateWindow(Ex), but only after the CreateWindow(Ex) call you have the window handle. Here's a solution based on Ben's next comment (thanks!):
// Window.h stays the same
// in .cpp
#include "Window.h"
#include <map>
std::map<HWND, Window*> window_map;
Window* currently_created_window = 0;
Window::Window(){
currently_created_window = this;
window_handle = CreateWindow(/*...*/);
}
LRESULT WINAPI Window::MessageProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam){
// if the key 'hWnd' doesn't exist yet in the map
// a new key-value pair gets created and the value gets value-initialized
// which, in case of a pointer, is 0
if(window_map[hWnd] == 0){
// window doesn't exist yet in the map, add it
window_map[hWnd] = currently_created_window;
}
window_map[hWnd]->InternalMessageProc(hWnd, msg, wParam, lParam);
}
Be cautious though, as the above example isn't thread-safe. You need to mutex-lock the creation of the window:
Window::Window(/*...*/){
Lock lock_it(your_mutex);
currently_created_window = this;
window_handle = CreateWindow(/*...*/);
lock_it.release();
// rest of the initialization
}
The above should do for the thread-safety (I hope).
You need to create window map and when you create new window just add it to this global map. You can use simple linked list instead of course.
map<HWND, Window *> wndmap;
LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wparam, LPARAM lparam)
{
Window *pWnd = wndmap [hwnd];
....
}
WndProc cannot be an instance member function, because Windows will not pass any hidden this parameter. It can be namespace scope or a static member.
One simple solution is to use a map<HWND, Window*> to find the object, and then forward parameters to a method on the object.
Note that WndProc can maintain the map itself, since CreateWindow provides an opaque user parameter that shows up in WM_CREATE which is useful for carrying the Window *, and then you remove the entry in WM_DESTROY.
Define your WndProc as a static class member - this will then be compatible (for all compilers I'm aware of) with non-member function pointer, such as those used in Win32 programming.
But I have to say that this is a bit of a waste of time - there are a zillion Windows class libraries out there, and I don't think the world really needs another one.
Sounds you need to declare the function without defining it. That's what prototypes are for.
class Object;
void f(Object* o);
class Object {
public:
...
void some_method() {
... &f ...
}
void another_method() {
...
}
...
};
void f(Object* o) {
...
o->another_method();
...
}
The other way around might also be possible.
class Object {
public:
...
void some_method();
void another_method();
...
};
void f(Object* o) {
...
o->another_method();
...
}
void Object::some_method() {
... &f ...
}
void Object::another_method() {
...
}
Quick sanity check: Is it possible to subclass a window using a functor? I'm running into a situation where I want to have some data available in the win proc, but GWLP_USERDATA is already being used. A functor seems like a good alternative, but I'm having trouble getting it to work.
Here's the basics:
class MyWinProc { // Win Proc Functor
public:
MyWinProc(ExternalClass* obj, HWND window) :
obj(obj), window(window) {
oldWinProc = SubclassWindow(window, this); // Apply Subclass
}
virtual ~MyWinProc() {
SubclassWindow(window, oldWinProc); // Remove Subclass
}
LRESULT CALLBACK operator()(HWND, UINT, WPARAM, LPARAM) {
switch( uMsg ) {
case WM_MOUSEMOVE: {
obj->onMouseMove(/*etc*/);
break;
}
}
return CallWindowProc(oldWinProc, hWnd, uMsg, wParam, lParam);
}
private:
ExternalClass* obj;
HWND window;
WNDPROC oldWinProc;
};
Seems all well and good, but when I hit DispatchMessage() in me message pump, I "Access Violation Writing Location 0x00000000", obviously not a good sign. Remove the call to the above code and life is happy again. :( So is this even possible, or am I going about it entirely the wrong way?
A CALLBACK function must be a static member function or an otherwise straight C-style function. The Windows API doesn't really know anything about C++ objects.
Something along the lines of this should work:
class MyWinProc {
public:
MyWinProc(ExternalClass* obj, HWND window) :
obj(obj), window(window) {
pContext = this;
oldWinProc = SubclassWindow(window, &MyWinProc::wndproc); // Apply Subclass
}
virtual ~MyWinProc() {
SubclassWindow(window, oldWinProc); // Remove Subclass
}
private:
static MyWinProc* pContext;
static
LRESULT CALLBACK wndproc( HWND, UINT, WPARAM, LPARAM) {
MyWndProc& me = *pContext;
// do your WndProc work...
}
ExternalClass* obj;
HWND window;
WNDPROC oldWinProc;
};
The problem with using a functor is the calling convention: Windows is expecting the address to be the address of a static function, and will use/invoke that address as such; whereas the 'this' which you're passing is not the address of a static function.
Windows is going to use the address like this (pseudo-coded assembly):
; push the necessary parameters
push [hWnd]
push etc...
; invoke the specified address (of the static function)
call [callback]
To invoke a functor, the Windows code would need to be like this
; push the necessary parameters
push [hWnd]
push etc...
; invoke the specified address (of the functor object)
; ... first, put the 'this' pointer as a hidden parameter into the ecx register
mov ecx,[callback]
; ... next, invoke the address (where is it?) of the class' functor method
call MyWinProc::operator()
... or instead of the last two statements, the following statements if the operator is virtual ...
; ... first, put the 'this' pointer as a hidden parameter into the ecx register
mov ecx,[callback]
; ... next, invoke the address of the operator via an (which?) entry
; in the class' vtable
call [ecx+8]
Neither of these is possible because the O/S isn't aware of the calling conventions for non-static C++ methods, especially including:
The way in which the implicit 'this' parameter is passed
The address of the class' non-virtual methods
The vtable entries of the class' virtual methods
GWLP_USERDATA is not the only way to store data associated with a window, you can also use SetProp().
And at least on x86, you can do ATL style thunking (A small piece of asm code that puts your class pointer in ecx and then jumps to your wndproc) You can find some links about that in a answer I posted here
GWLP_USERDATA is already being used
I don't know what your SubclassWindow function is, but CWnd::SubclassWindow says, "The window must not already be attached to an MFC object when this function is called".
I'm running into a situation where I want to have some data available in the win proc
A usual (non-MFC) way to implement that is to have a global/static dictionary, whose key/index is the HWND value of the subclassed windows, and whose data is the data that you want to associate with that window: that data is often the this pointer of a C++ class of yours.
You subclass the window procedure with a static callback function of yours: your static callback function then, when it's invoked, uses the HWND which it's passed to look up the data in the static dictionary.
You can still use the value stored in GWLP_USERDATA...
class MyWinProc { // Win Proc Functor
public:
MyWinProc(ExternalClass* obj, HWND window) :
obj(obj), window(window) {
oldUserData = GetWindowLongPtr(GWLP_USERDATA);
oldWinProc = SubclassWindow(window, this); // Apply Subclass
}
virtual ~MyWinProc() {
SubclassWindow(window, oldWinProc); // Remove Subclass
}
LRESULT CALLBACK operator()(HWND, UINT, WPARAM, LPARAM) {
switch( uMsg ) {
case WM_MOUSEMOVE: {
obj->onMouseMove(/*etc*/);
break;
}
}
LONG userDataToRestore = SetWindowLongPtr(GWLP_USERDATA, oldUserData);
LRESULT lRet = CallWindowProc(oldWinProc, hWnd, uMsg, wParam, lParam);
SetWindowLongPtr(GWLP_USERDATA, userDataToRestore);
}
private:
ExternalClass* obj;
HWND window;
LONG oldUserData;
WNDPROC oldWinProc;
};