"SendMessage" to 3 different processes in C++ - c++

I want to send keystrokes to multiple processes. For example, if I press “1”, then I want to send the “1” to 3 "Notepad windows". Frist I want to try to send a keystroke to notepad, but it fails on the HWND:
//HANDLE hWin;
HWND windowHandle = FindWindowA(NULL, "Notepad"); //Can’t find a proccess
//Send a key
if( windowHandle ) //This one fails
{
while(true)
{
if( GetAsyncKeyState(VK_F12) != 0 )
{
SendMessageA(windowHandle, WM_KEYDOWN, VK_NUMPAD1, 0);
Sleep(1000);
SendMessageA(windowHandle, WM_KEYUP, VK_NUMPAD1, 0);
}
Sleep(100);
}
}
But the "FindWindow" method is not good enough for my program. There is also no way to get 3 different processes with the same name. So how can I make 3 handles to 3 different processes with the same name? And how can I send key’s to the processes?

You can use EnumWindows for enumerating all the top level windows on the system. You then need to filter through these windows to get the ones you are interested in. Class name is probably a better choice for filtering rather than the window name though. Here is some example code (not tested) of what I have in mind:
BOOL CALLBACK BroadcastToNotepad(HWND hwnd, LPARAM lParam)
{
wchar_t lpClassName[16];
/*
* More reliable to filter by class name. We could additionally filter
* by caption name too if necessary.
*/
if(GetClassName(hwnd, lpClassName, _countof(lpClassName))) {
if(wcscmp(lpClassName, L"Notepad") == 0) {
SendMessage(hwnd, WM_KEYDOWN, (WPARAM)lParam, 0);
Sleep(1000);
SendMessage(hwnd, WM_KEYUP, (WPARAM)lParam, 0);
}
}
return TRUE;
}
// Some handler which gets invoked when your hotkey is hit.
void handlerKey1(...)
{
EnumWindows(BroadcastToNotepad, (lParam)VK_NUMPAD1)
}
Note the usage of BroadcastToNotepad and how you can have different handlers pass in a different lParam.
One final thing to note is that PostMessage/SendMessage is not a reliable way to simulate keyboard input. This is noted by Raymond Chen here. SendInput is the preferred way for injecting input. However, to use that you will need to ensure the window you want to send to has the keyboard focus.
I recall vaguely having played with something similar to what you are doing in the past. If I remember correctly, you need to send to Notepad's child window (class name = Edit). So the code above needs to be modified as so:
if(wcscmp(lpClassName, L"Notepad") == 0) {
HWND hwndChild = FindWindowEx(hwnd, NULL, L"Edit", NULL);
SendMessage(hwndChild, WM_KEYDOWN, (WPARAM)lParam, 0);
Sleep(1000);
SendMessage(hwndChild, WM_KEYUP, (WPARAM)lParam, 0);
}

Firstly install Spy++ from Visual Studio which lets you see all the HWND windows in hierarchy ( and which process owns them).
Then you'll see why your FindWindow is failing. You'll also know the exact hierarchy calls to make on FindWindow and GetWindow().
Be aware that since Vista some HWNDs are protected and you cant send to them - but notepad is probably fine.
For sending the key, you can probably just use PostMessage to fire and forget.

First of all, why is while(true) there? Wouldn't you rather want to activate your software on F12 key press than having an infinite loop? That handle is not valid forever, you know.
Second, you'd probably want to use EnumWindows to go through all the windows and find the one you're interested in. Then you'd implement a callback function that'll need to decide on some basis if it wants to act on some window or not (be it name or something else).
SendMessage/SendMessageA/SendMessageW should work just fine when you've found a proper handle for the window you want to target for (save for some special windows that are protected from this).

Related

How can I make OpenGL and GDI both working properly at the same time?

I have four windows, which are one parent window and three child windows. I want to make two of those child windows to draw stuff. The first child window is using OpenGL, and the second child window is using GDI. If I just draw some stuff on my OpenGL window and everything works fine, but when I try to draw(or just try to process WM_PAINT message) something else on my GDI window, those child windows become weird. Firstly, some parts(like buttons, statics, title bar) of my third child window will be missing. Secondly, if I try to resize any of those windows, one or two child windows will be missing. But once I click those windows they will be back. Thirdly, PeekMessage does not work anymore, it always return a FALSE, MessageBox seems not to work properly(I cannot see the popup window, but I can hear the sound), either.
My third child window just created.
After I click it.
I thought there might be something wrong with the message processing, but I cannot figure out what is actually happening. Is here anyone has any suggestions?
Message Loop:
MSG msg;
DWORD dwLast;
DWORD dwCurrent;
DWORD dwInterval = 20;//50 FPS 1000 / 50
dwLast = GetTickCount();
while (1) {
while (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE) == FALSE)
{
dwCurrent = GetTickCount();
if (dwCurrent - dwLast < dwInterval)
continue;
SendMessage(Handle_Child_Demo, WM_PAINT, 0, 0);
dwLast = dwCurrent;
}
if (GetMessage(&msg, NULL, 0, 0) != TRUE) {
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
I am not using MDI to create my child windows, I just used CreateWindow to create all my child windows, and I think that must be something wrong with it, what else do I need to do to make sure those child windows work properly?
MUST USE MDI to create child windows, just remember, USE MDI!!!! Or there will be something really weird, this is bacese those messages are not processed properly, and MDI will help us to do it.

Why does c++ send WM_DRAWITEM to the parent process?

I started recently learning C++ and WinAPI, I want to be able to create my own programs
I am subclassing a button (into separate file, because I like things clean and organized - is that a bad idea?), because I want to have few of the kind with same parameters. I also want to draw it, and the question that pops to my mind is: wouldn't it be better to have it all in the class file? Meaning all parameters including custom draw. It is annoying to go to main file to change the looks and set all other parameters in the class file. I use codeblocks.
EDIT (explanation):
#include <Windows.h>
#include <Winuser.h>
#include "CustomButton.h"
/*global vars*/
WNDPROC CustomButton::CustomButtonLongPtr;
/*functions*/
LRESULT CALLBACK CustomButtonProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
CustomButton * CustomButton::CreateCustomButton(HINSTANCE hInstance, HWND hwnd, int pos_x, int pos_y, int width, int height)
{
CustomButton * p_CustomButton = new CustomButton;
HWND customButton = CreateWindowEx(0, "BUTTON", "OK", WS_VISIBLE | WS_CHILD | BS_OWNERDRAW, pos_x, pos_y, width, height, hwnd, (HMENU)200, (HINSTANCE)GetWindowLong(hwnd, GWLP_HINSTANCE), p_CustomButton);
if(customButton == NULL)
{
delete p_CustomButton;
MessageBox(NULL, "Problem creating the Search box.", "Error", 0);
return 0;
}
CustomButton::CustomButtonLongPtr = (WNDPROC)SetWindowLongPtr(customButton, GWLP_WNDPROC, (LONG_PTR)&CustomButton::CustomButtonProc);
return p_CustomButton;
}
I want to use WM_DRAWITEM for this button in CustomButtonProc and I am wondering why did the developers think that it would be smarted to allow to use it only in parent WinProc.
This is a little complicated to explain.
You're probably coming from a background where you plug a function into an outlet to handle events, something like
extern void onClicked(void);
button->OnClicked = onClicked;
And while it's fully possible for Windows to have done this from the start, you have to remember that Windows was originally designed to run on systems with severely limited memory, so it was important that controls not waste memory. And there are a lot of events you can get from a button:
void (*OnClicked)(void);
void (*OnDoubleClicked)(void);
void (*OnDisabled)(void);
void (*OnHighlight)(void);
void (*OnKillFocus)(void);
void (*OnPaint)(void);
void (*OnSetFocus)(void);
void (*OnUnhighlight)(void);
void (*OnUnpushed)(void);
HBRUSH (*OnCtlColorButton)(void);
Having these for every button in your program — that is, push buttons, checkboxes, radio buttons, and groupboxes — with most of them likely to be unused would just be a massive waste of memory.
Because Windows needs a way to communicate between the system and a window and between windows, Microsoft decided to create a message-passing interface where each message had a 16-bit code and two pointer-sized (originally one 32-bit and one 16-bit) parameters and a pointer-sized return value. And there aren't a lot of messages that Windows needs for itself, giving both window classes and the application a lot of real estate for using messages to communicate. So why not use a message to signal the event?
Using a message avoids the waste of memory while still allowing the button to pass data to and return data from its target window. So the logic follows that all a button would need to do is
/* this is not the correct syntax but let's use it for expository purposes */
#define BN_CLICKED someNumberHere
case WM_LBUTTONUP:
SendMessage(GetParent(hwnd), BN_CLICKED, hwnd);
break;
and the parent would handle that:
case BN_CLICKED:
if (whichButton == button1)
doButton1Stuff();
break;
No wasted memory, but still flexible and extensible. And even more importantly, also binary-compatible: if more events were added later, the size of the function pointer table would need to change, and newer programs that tried to use newer events on older systems would clobber random memory. With messages, these programs would just have dead code.
Now why send the message to the parent? If we view windows as communication endpoints, then this is obvious: you want the button to tell its parent that it was clicked because you're communicating that the button was clicked!
But more important, you didn't write the button's window procedure. Microsoft did, and they provide the same one to every program. If you could handle the message in the button procedure, where would you put it? You can't change the button procedure, after all.
(Nowadays we have something called "subclassing" which allows you to override a single window's window procedure to do custom processing. It's not used for event handling because it's more work than just sending up to the parent.)
All of this extends to custom draw; just substitute "custom draw" for "clicked" and it should still make sense. Hopefully this explanation was clear, even with that mental substitution.
If you want, you can write your own facility to handle events in the function pointer way. Keep a map of window handles to event functions and call a global dispatch function in all your window procedures to handle the event messages WM_COMMAND, WM_NOTIFY, and (for trackbars) WM_HSCROLL and WM_VSCROLL. How you do this is up to you, but think about whether you really want to do it this way; sometimes it's necessary, but sometimes it isn't. If you do, remember to provide a way to pass arbitrary data to the event function that's decided at event connection time, so the event handler can do something reasonable without relying on global state.
Thanks to comments by RemyLebeau and IInspectable I was able to also find solution to my frustration, which I am going to explain here for anybody else who's scratching their heads over this very issue.
This solution does not require VCL nor any component from Visual Studio and such.
First define your own custom message, in the way that you can reach it inside WndProc:
#define MY_DRAWITEM (WM_APP+1)
UINT uDrawButtonMsg = RegisterWindowMessage(_T("MY_DRAWITEM"));
Then find out what number it is assigned:
std::cout << uDrawButtonMsg; //for example 49648
And send this message from WndProc to your subclassed control from any message you wish, for example WM_DRAWITEM:
case WM_DRAWITEM:
{
::SendMessage(p_CustomButton->customButton, uDrawButtonMsg, wParam, lParam);
break;
}
And then in your subclass just catch the message by the 5 digit number you looked for while ago:
if(49648 == uMsg)
{
//do your DRAWITEM stuff here
}
Thanks to everybody who contributed to this article helping with exaplanation, tips and also historical background!

How do I detect the addition of a new monitor?

I have a windowless program that handles some window management hotkeys. I'd like to provide features such as the ability to move a window between monitors. I've used EnumDisplayMonitors to enumerate all existing monitors in the system, and I've written code to handle WM_DEVICECHANGE, but I'm not actually receiving the message.
Here's my message loop:
// I've tried GetMessage(&msg, (HWND) NULL, 0, 0) here too
while (GetMessage(&msg, (HWND) -1, 0, 0) > 0)
{
int key;
int mod;
MessageBox(NULL, (LPCWSTR) ((std::wostringstream&) (std::wostringstream() << L"You got a message: " << msg.message)).str().c_str(), L"Got Message", MB_OK);
switch (msg.message)
{
case WM_HOTKEY:
key = HIWORD(msg.lParam);
mod = LOWORD(msg.lParam);
if (mod != MOD_WIN) continue;
ProcessHotkey(key);
break;
case WM_DEVICECHANGE:
InitMonitorInfo();
}
}
The program compiles and runs fine, and the hotkeys work. Upon adding or removing a monitor though, nothing happens. The message box to indicate a message has been received never appears.
I suppose I could just poll the monitor configuration every 5 seconds, but that's not the right way to solve the problem.
Do I need to actually create a window to receive WM_DEVICECHANGE? Because I don't. The hotkeys post their messages to NULL when they fire since they're not bound to a window, to be handled by the main thread.
You must create a window to get the WM_DEVICECHANGE message.
WM_DEVICECHANGE is a message that's broadcast, SendMessage(HWND_BROADCAST,...) style. Only top-level windows can receive it. The window doesn't need to be visible so there's little reason to look for an alternative.
RegisterDeviceNotification() is an alternative. But that still needs a window. Or a service handle, but you don't want to move windows around from a service. They run in an isolated session with their own desktop. So creating a window is a hard requirement.

C++ subclassing a form to trap F1 - F12 keys

The main form opens a child form that has a handful of button CONTROLs on it. I need to trap keyboard events so I subclassed one of the controls. All is good until the control loses focus of course.
Ideally, as long as this child form is open I would like to assign the focus to this control and thus trap all the keystrokes, no matter where the user clicks.
I suspect superclassing might be a better way to go but I am not as familiar with it.
Perhaps what I should do is use accelerators on the main form?
ADDED:
I should mention that the main form has a large listview control that is subclassed to recover up/down arrows and mousewheel etc.
The traditional way is to install a keyboard hook (SetWindowsHookEx), but you need to inject it into every application, and it doesn't work across 32/64 bit boundaries.
What you can do however, and quite easily at that, is to poll the keyboard with GetKeyboardState on a timer and check whether your f1-f12 keys are activated. The timer can be as slow ticking as 100ms and it will catch almost everything while using virtually no resources.
Assuming that this is within Windows and the Win32 API, one option is to look for messages in your main GetMessage, TranslateMessage, DispatchMessage loop. You can special-case any message within this loop, irrespective of which window it's aimed at.
You should probably use IsChild to check that the message is intended for a control on your main window (as opposed to some dialog box or message box that might be displayed separately). Getting the logic right can be fiddly, too. It would be best to only intercept messages when you know your control has lost the focus, and only intercept the exact messages you need to.
Years ago, I wrote a library message loop with a lot of this built in. I had a simple manager class that held pointers to instances of my own little window class. The loop knew the difference between dialogs and normal windows, gave each window class a chance to spy on its childrens messages, and so on. You won't be able to run this directly and the conventions are a bit strange, but you might find this useful...
int c_Window_List::Message_Loop (void)
{
MSG msg;
bool l_Handled;
while (GetMessage (&msg, NULL, 0, 0))
{
l_Handled = false;
c_Windows::c_Cursor l_Cursor;
bool ok;
for (ok = l_Cursor.Find_First (g_Windows); ok; ok = l_Cursor.Step_Next ())
{
if (IsChild (l_Cursor.Key (), msg.hwnd))
{
if (l_Cursor.Data ().f_Accelerators != NULL)
{
l_Handled = TranslateAccelerator (l_Cursor.Key (), l_Cursor.Data ().f_Accelerators, &msg);
if (l_Handled) break;
}
if (l_Cursor.Data ().f_Manager != 0)
{
l_Handled = l_Cursor.Data ().f_Manager->Spy_Msg (l_Cursor.Key (), msg);
}
if (l_Handled) break;
if (l_Cursor.Data ().f_Is_Dialog)
{
l_Handled = IsDialogMessage (l_Cursor.Key (), &msg);
if (l_Handled) break;
}
}
}
if (!l_Handled)
{
TranslateMessage (&msg);
DispatchMessage (&msg);
}
if (g_Windows.Size () == 0)
{
// When all windows have closed, exit
PostQuitMessage (0);
}
}
return msg.wParam;
}
The f_ prefixes mean field - I picked up the m_ convention later, but this code hasn't been revisited in a very long time. f_Manager in particular points to an instance of my c_Window_Base class. The c_Cursor class is a kind of iterator, used to step through all the windows stored in the g_Windows variable (actually a static class member rather than a global).

How to send a link to an application, like Spotify does

When we save a level in our editor, we create a log file of any errors it contains. These consist basically of an error message and a path that allows the user to find the erronous item in a tree view.
What I want is to make that path a link, something like
< a href="editor://path/to/gameobject" > Click to see object in editor< /a >
The SO questions I've seen regarding this seems to point to this msdn page:
http://msdn.microsoft.com/en-us/library/aa767914.aspx
But from what I can tell, it will spawn a new instance of the application. What I want to do is to simply "call" our editor somehow. One way to do it, I guess, is to spawn it, and in the beginning check if there's already an instance running, and if so, send the commandline to it.
Is that the best way to do it? If so, any ideas on how to do it best? What are otherwise some ways that this could be done?
Also: does the msdn solution work across browsers? Our editor runs in Windows only, but people use IE, Fx, GC and Opera.
If you need the link to work in any viewer, yes, registering a protocol handler is the best way.
As for launching the editor, you could implement it as an out-of-process COM server, but if you've already got command line parsing sorted, you might as well use a window message or named pipe to pass that to the editor. If you're sending a window message, you could use FindWindow (with a unique class name) to check for a running instance.
Sounds like you solved it already, by checking for a previous instance.
I would be surprised if the OS takes upon it to somehow "stamp" the association with data telling it to separate programs that should run multiple times from programs that should not.
Here's how I solved it. Basically, there are two parts. Or three.
First, the app needs to register itself in the registry, like this. It took some googling to find out how to use the windows register functions, but they were pretty straightforward. By adding this to the registry, your application will launch when a link with your custom url protocol is clicked.
Secondly, the app needs to detect that it's been started from a browser. Obviously quite trivial, just check the command line for "/uri" or however you chose to customize it.
Third, you don't actually want to start your application - it should already be running! Instead, when you've detected that you got started from a hyperlink, you need to detect if another instance of the application is already running. After that, you need to pass the command line to it. Here's how I did it:
bool ShouldContinueStartEditor( const std::string& command_line )
{
// Check if this instance was spawned from a web browser
if ( command_line.find( "/uri" ) != std::string::npos )
{
// Try to find other instance of JustEdit
HWND wnd = FindWindow( "AV_MainFrame", NULL );
if ( wnd )
{
COPYDATASTRUCT cds;
NEditorCopyData::SCommandLine data_to_copy;
strncpy( data_to_copy.m_CommandLine, command_line.c_str(), sizeof(data_to_copy.m_CommandLine) - 2 );
cds.dwData = NEditorCopyData::ECommandLine; // function identifier
cds.cbData = sizeof( data_to_copy ); // size of data
cds.lpData = &data_to_copy; // data structure
SendMessage( wnd, WM_COPYDATA, NULL, (LPARAM) (LPVOID) &cds );
}
return false;
}
return true;
}
"AV_Mainframe" is the name of the hwnd. If you happen to be using WTL, you can declare it like this.
DECLARE_FRAME_WND_CLASS("AV_MainFrame", IDR_MAINFRAME)
Now, in your window class, you need to handle the WM_COPYDATA message like this:
MESSAGE_HANDLER(WM_COPYDATA, OnCopyData);
LRESULT OnCopyData(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
LRESULT CMainFrame::OnCopyData(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/)
{
PCOPYDATASTRUCT cds = (PCOPYDATASTRUCT) lParam;
if ( cds->dwData == NEditorCopyData::ECommandLine )
{
NEditorCopyData::SCommandLine* command_line = static_cast( cds->lpData );
const char* internal_path = strstr( command_line->m_CommandLine, "/uri" );
if ( internal_path != NULL )
{
// Do your thang
}
}
return 0;
}
And that's pretty much all there's to it. Oh, this is what the copy data namespace looks like:
namespace NEditorCopyData
{
enum ECopyDataMessages
{
ECommandLine = 0
};
struct SCommandLine
{
char m_CommandLine[512];
};
}