2007-09-26

Receive windows message

Recently, I work on how to receive windows message.
In fact, there's two way to achieve this.

If you have MFC window, or your AP is already a window, it's easy to handle all kinds of messages as long as you overwrite this function, PreTranslateMessage.

However, how about there's no any window in your AP?

The answer is we can create a window for your AP to receive windows message.

Firstly, set your dummy window properties and set the function to receive window message by assigning function pointer to lpfnWndProc. (We call dummy window because it doesn't have its own form, it is just used for some purpose)

WNDCLASS wc;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = (WNDPROC) DummyWndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = _AtlBaseModule.GetModuleInstance();
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszMenuName = NULL;
wc.lpszClassName = CLMLSVC_CLASS_NAME;


Second, register and create this window.
RegisterClass(&wc);
m_hDummyWnd = ::CreateWindow(CLMLSVC_CLASS_NAME,
L"",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0,
CW_USEDEFAULT, 0,
NULL, NULL, _AtlBaseModule.GetModuleInstance(), NULL);

Finally, pass some user data for later use. We'll know why we use this.
if (IsWindow(m_hDummyWnd))
::SetWindowLong(m_hDummyWnd, GWL_USERDATA, (long)this);
Now, to handle the message, we just implement the function mentioned above.
LRESULT CALLBACK CMLSvc::DummyWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
Note that, if we want to use the user data we passed previously, just write this line in the function.
CMLSvc* pCLMLSvc = (CMLSvc*)::GetWindowLong(hWnd, GWL_USERDATA);

沒有留言: