MS Word COM addin can't receive messages in XP - c++

From inside my COM addin I create a dialog, and I then send messages to it from an external process. I use HWND_BROADCAST and RegisterWindowMessage.
But those messages are never received by the dialog proc of the COM addin. I know this because I log all the messages received by the dialog proc, and also the value returned by RegisterWindowMessage.
From the external process:
static UINT nCloseMessage = 0;
if (!nCloseMessage)
nCloseMessage = RegisterWindowMessage(_T("MyCloseMessage"));
PostMessage(HWND_BROADCAST, nCloseMessage, 0, 0);
From the COM add-in:
INT_PTR CALLBACK ProgressDialogProc(__in HWND hwndDlg,__in UINT uMsg,__in WPARAM wParam,__in LPARAM lParam)
{
static UINT nCloseMessage = 0;
if (!nCloseMessage)
nCloseMessage = RegisterWindowMessage(_T("MyCloseMessage"));
if (uMsg == nCloseMessage)
MessageBox(0,_T("Caught"),0,0);
return FALSE;
}

I found why I get this error, HWND_BROADCAST doesn't work when the dialog has a parent window.
Passing NULL to CreateDialog for the parent fixed the error.

Related

PostMessage(), SendMessage not working in ATL dll (event handling)

sorry, my english skill is very low.
i make a ATL(C++) dll. and handled by VB.
i make under base code.
WaitAndReadData, Thread_WaitAndReadData is working.
but, ::SendMessage, ::PostMessage is not working in Thread_WaitAndReadData or WaitAndReadData.
and breakpoint not working in Get_Data_Messagehandler.
(+ another function call.)
#define WM_SERVERTHREADFIREEVENT (WM_USER+2)
BEGIN_MSG_MAP(CHello)
CHAIN_MSG_MAP(CComControl<CHello>)
MESSAGE_HANDLER(WM_SERVERTHREADFIREEVENT, GetData_Messagehandler)
DEFAULT_REFLECTION_HANDLER()
END_MSG_MAP()
-
static DWORD WINAPI Thread_WaitAndReadData(LPVOID pParam)
-
STDMETHODIMP CHello::WaitAndReadData(BSTR* ret_Result)
{
// TODO: Add your implementation code here
DWORD dwThreadID;
thread = CreateThread(NULL, 0, Thread_WaitAndReadData, (LPVOID)this, 0, &dwThreadID);
return S_OK;
}
-
DWORD WINAPI CHello::Thread_WaitAndReadData(LPVOID pParam)
{
CHello* hello = (CHello*)pParam;
::SendMessage(hello->m_hWnd, WM_SERVERTHREADFIREEVENT, (WPARAM)NULL, (LPARAM)NULL);
return S_OK;
}
-
LRESULT CHello::GetData_Messagehandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
MessageBox(L"GetData_Messagehandler", L"asd", MB_OK);
return 0;
}
Even though MSDN states that there is no marshaling of WM_USER + x messages in cross-process sending, if my memory serves me right you might have troubles with cross-thread sending as well. In this case use RegisterWindowMessage API to obtain "sendable" WM_xxx identifier rather than harcoding it using a #define
Don't use bare CreateThread, use AtlCreateThread instead (or, _beginthreadex). See why.
Another reason to not receive messages on window thread is thread deadlock or window creation on thread that does not have a message pump later on, in both cases a message might be sent but there is no dispatching it to window. You can also use Spy++ tool (spyxx.exe in Visual Studio Comment\Tools directory) to make sure that the message in question is indeed being sent to the window.

C++: Trying to hook a message box and change its position

I recently started coding in C++ and I am very new to it. (I code in Javascript, PHP, Java and Obj-C more often)
I'm practicing how to hook a message box and change its position. This is what I have in my .cpp file (after reading this SO post).
#include <iostream>
#pragma comment(lib,"User32.lib")
#include <windows.h>
HHOOK hhookCBTProc = 0;
LRESULT CALLBACK pfnCBTMsgBoxHook(int nCode, WPARAM wParam, LPARAM lParam){
if (nCode == HCBT_CREATEWND)
{
CREATESTRUCT *pcs = ((CBT_CREATEWND *)lParam)->lpcs;
if ((pcs->style & WS_DLGFRAME) || (pcs->style & WS_POPUP))
{
HWND hwnd = (HWND)wParam;
SetWindowPos(hwnd, HWND_TOP,130,122, 0, 0,SWP_NOSIZE);
}
}
return (CallNextHookEx(hhookCBTProc, nCode, wParam, lParam));
}
int main(void)
{
hhookCBTProc = SetWindowsHookEx(WH_CBT,pfnCBTMsgBoxHook,
0, GetCurrentThreadId());
int sResult = MessageBox ( NULL, "Hooked!", "oh my", MB_OK );
UnhookWindowsHookEx(hhookCBTProc);
return 0;
}
For some reason the position of the message box isn't changing. Where did it go wrong?
(I know I can create a customized window or dialog. But I am doing it this way because I want to learn how to hook a message box and where I did wrong.)
Firstly you should check in the debugger that your hook is actually being called, if you haven't already.
Secondly, at the time the HCBT_CREATEWND hook event is triggered, the window has only just been created - the system has yet to size and position it. It will do this with the values in the CREATESTRUCT after the hook returns - overriding your SetWindowPos call.
See the docs from MSDN on the lParam value for this particular hook event:
Specifies a long pointer to a CBT_CREATEWND structure containing
initialization parameters for the window. The parameters include the
coordinates and dimensions of the window. By changing these
parameters, a CBTProc hook procedure can set the initial size and
position of the window.
Therefore, the correct way to use this hook to change a window's position is to modify the values in the CREATESTRUCT directly.
Also note that it's quite possible that the dialog manager sizes and positions the window after creation, so if you find that this still isn't working for you, you may need to try watching for the HCBT_MOVESIZE event instead.
From the docs
At the time of the HCBT_CREATEWND notification, the window has been
created, but its final size and position may not have been determined
and its parent window may not have been established.
Maybe try hooking into CBT_ACTIVATE instead.

find lpClassName of started application to be used in FindWindow wniapi c++?

How can i find the lpClassName string of the FindWindow API call
if i start application with CreateProcess API function
PROCESS_INFORMATION ProcessInfo; //This is what we get as an [out] parameter
STARTUPINFO StartupInfo; //This is an [in] parameter
ZeroMemory(&StartupInfo, sizeof(StartupInfo));
StartupInfo.cb = sizeof StartupInfo ; //Only compulsory field
if(CreateProcess("c:\\temp\\application1.exe", NULL,
NULL,NULL,FALSE,0,NULL,
NULL,&StartupInfo,&ProcessInfo))
{
WaitForSingleObject(ProcessInfo.hProcess,INFINITE);
CloseHandle(ProcessInfo.hThread);
CloseHandle(ProcessInfo.hProcess);
}
else
{
MessageBox("The process could not be started...");
}
also can i some how set only part of the name in the FindWindow ?
for example if i know that allays the app name is "application< some version number>.exe"
so it can be :
application1.exe
application1.1.exe
application1.2.1.exe
my final goal is to use Windows Message system and the SendMessage API method to send messages to the application.
It sounds like what you really want is the handle to the window created by your launched application.
The problem is, your process might create many windows. You can use the SetWindowsHookEx function to be notified whenever the process creates a new window.
Untested code incoming:
LRESULT CALLBACK CBTProc(int nCode, WPARAM wParam, LPARAM lParam) {
if(nCode == HCBT_CREATEWND) {
// wParam is a handle to a window your app just created.
}
return 0;
}
CreateProcess("c:\\temp\\application1.exe", NULL,
NULL,NULL,FALSE,CREATE_SUSPENDED,NULL,
NULL,&StartupInfo,&ProcessInfo);
SetWindowsHookEx(WH_CBT, procHook, NULL, ProcessInfo.hThread);
ResumeThread(ProcessInfo.hTread);

crash on ShowWindow()

I am developing a Notepad++ plugin.
I have a simple dialog box, which is created using CreateDialogParam(). It is initially hidden.
After a menu click, I call ShowWindow() with SW_SHOW on its handle, which results in this exception:
c000041d
Upon debugging , I found that these two messages are sent to my dialog just before crash
WM_SHOWWINDOW
WM_WINDOWPOSCHANGING
Both of them, I am not handling. Here is my dlgproc code. Any idea why it would happen ?
BOOL CALLBACK StaticDialog::dlgProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INITDIALOG :
{
// Get the additional init data
StaticDialog *pStaticDlg = (StaticDialog *)(lParam);
// Store the handle in the object
pStaticDlg->_hSelf = hwnd;
::SetWindowLongPtr(hwnd, GWL_USERDATA, (long)lParam);
// Store the co-ordinates in the object
::GetWindowRect(hwnd, &(pStaticDlg->_rc));
// Forward the message for further processing
pStaticDlg->run_dlgProc(message, wParam, lParam);
// TRUE if it processed the message
return TRUE;
}
default :
{
// Retrieve the user data
StaticDialog *pStaticDlg = (StaticDialog *)(::GetWindowLongPtr(hwnd, GWL_USERDATA));
if (!pStaticDlg)
return FALSE;
// Send the message for further processing
return pStaticDlg->run_dlgProc(message, wParam, lParam);
// return FALSE if it processed the message
}
}
}
BOOL CALLBACK MarkDownViewDialog::run_dlgProc( UINT Message, WPARAM wParam, LPARAM lParam)
{
switch (Message)
{
case WM_INITDIALOG:
{
EmbedBrowserObject(this->_hSelf);
DisplayHTMLPage(this->_hSelf,L"http://www.microsoft.com");
DisplayHTMLStr(this->_hSelf, L"<H2><CENTER>HTML string test</CENTER></H2><P><FONT COLOR=RED>This is a <U>HTML string</U> in memory.</FONT>");
break;
}
default:
break;
}
return FALSE;
}
The dialog box is created through plugin mechanism of Notpead++. I am putting the source code from its file StaticDialog.cpp. The control goes through else block in code below.
void StaticDialog::create(int dialogID, bool isRTL, bool isModeles)
{
if (isRTL)
{
DLGTEMPLATE *pMyDlgTemplate = NULL;
HGLOBAL hMyDlgTemplate = makeRTLResource(dialogID, &pMyDlgTemplate);
_hSelf = ::CreateDialogIndirectParam(_hInst, pMyDlgTemplate, _hParent, (DLGPROC)dlgProc, (LPARAM)this);
::GlobalFree(hMyDlgTemplate);
}
else
_hSelf = ::CreateDialogParam(_hInst, MAKEINTRESOURCE(dialogID), _hParent, (DLGPROC)dlgProc, (LPARAM)this);
//int i=GetLastError();
if (!_hSelf)
{
//systemMessage(_T("StaticDialog"));
return;
}
if (isModeles) {
_isModeles = isModeles;
::SendMessage(_hParent, NPPM_MODELESSDIALOG, MODELESSDIALOGADD, (WPARAM)_hSelf);
}
}
My entire solution source code is hosted here:
https://github.com/madhur/Npp-Markdown-Viewer
Issue Resolution
Here is what I have done to troubleshoot the problem:
Created a Win32 project in which I create a dialog box and put exactly same source code to embed browser control in WM_INITDIALOG and it works. This Win32 project links with the same static library, which the original source code is linking with. This is the source of the sample project mail file:
https://github.com/madhur/Npp-Markdown-Viewer/blob/master/dll/example/example.c
The static library I referenced above, is nothing but it contains functions to embed browser control in HWND and to render either an URL or string. I have taken the source from here: http://www.codeguru.com/Cpp/I-N/ieprogram/article.php/c4379
This is the source of static library main file:
https://github.com/madhur/Npp-Markdown-Viewer/blob/master/dll/dll.c
If I comment this single line, the plugin works, basically it loads the dialog box without the Browser control in it:
EmbedBrowserObject(this->_hSelf);
The actual exception in Visual Studio is raised on this line:
return pStaticDlg->run_dlgProc(message, wParam, lParam);

C++ Console app, SetWindowsHookEx, Callback is never called

I have a little console application that has an embedded v8 engine, and I would like to add a hook to register key events. This all worked before when I was using Qt and QtScript, but I am porting it all over to straight C++ in VC++ 2008. The application compiles and runs, but the hook is never called, here is the relevant code:
In main()
HWND hwndC = GetConsoleWindow() ;
HINSTANCE hInst = (HINSTANCE)GetWindowLong( hwndC, GWL_HINSTANCE );
if (SetWindowsHookEx(WH_KEYBOARD_LL, HookProc, hInst, NULL) == 0) {
printf("Failed to set hook\n");
} else {
printf("Hook established\n");
}
g->RunScript(argc,argv);
And the proc:
LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
printf("HookProc called\n");
PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT) (lParam);
if (wParam == WM_KEYDOWN) {
keyDown(p,g);
} else if (wParam == WM_KEYUP) {
keyUp(p,g);
}
fflush(stdout);
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
This is essentially an expansion on shell.cc from the v8 sample code. I wonder if it is somehow blocking? I admit to not really knowing what I am doing here, just playing around and learning but this one has me stumped.
Inside of keyDown say, I have something like this:
v8::Handle<v8::String> callback_name = v8::String::New("onKeyDown");
v8::Handle<v8::Value> callback_val = g->_context->Global()->Get(callback_name);
if (!callback_val->IsFunction()) {
printf("No onKeyDown handler found\n");
return;
}
v8::Handle<v8::Function> callback = v8::Handle<v8::Function>::Cast(callback_val);
const int argc = 1;
v8::Handle<v8::Value> argv[argc] = { v8::Int32::New(char(p->vkCode)) };
printf("Calling onKeyDown\n");
v8::Handle<v8::Value> result = callback->Call(g->_context->Global(), argc, argv);
Some of this may actually not work in the end, but it just never gets called, when I run the program, and define: onKeyDown = function(key) {...}; I can see that onKeyDown is working just fine, I can use all of my bound c++ method etc from JS, so this thing is just driving me batty.
Any help, maybe pointers to some educational materials would be much appreciated.
Just to be clear, this function in c: LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam) is never getting called, or never seeing a printf, and the output at the start says: Hook established, so windows is reporting the hook is established.
/Jason
A low-level hook, like WH_KEYBOARD_LL requires that your application pumps a message loop. That's the only way that Windows can break into your thread and make the call to the HookProc callback you registered.
A console mode app doesn't pump a message loop like regular Windows GUI apps do. Judging from your snippet, it isn't going to be easy to add one either. You'll need to create a thread.
Maybe this function will be of help to you?
GetAsyncKeyState