How windows manages to send messages with more than two parameters? - visual-studio-2010

Studying about message-handling in MFC, I've found that:
A message comes with 2 parameters that give you more information about the event. Each parameter is a 32-bit value: lParam and wParam.
So when I created a user-defined message wwith no parameters, I sent it with the code:
pParentOfClass ->SendMessage(WM_RECTANGLECHANGED,0,0);
but just to be curious, how windows manages to send messages with more than two parameter like WM_SIZE.

As it was already quickly stated in the comment by Roger Rowland, multiple parameters are often packed into the low and/or high order of the LPARAM and WPARAM parameters when using messages.
What you probably mean by more parameters than two, is the fact that MFC has it's own event handler wrappers which already took the necessary information from the LPARAM and WPARAM parameters and forwarded it to it's own event handler implementations, which of course can have as many parameters as desired.
Example with WM_SIZE:
Originally, the WM_SIZE message is sent with LPARAM containing some flags and WPARAM containing width and height (through packing into low and high order).
Now MFC receives that message, gets all info it thinks is necessary for the user and calls its own event handler:
afx_msg void OnSize(
UINT nType,
int cx,
int cy
);
That's basically it.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms632646%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/h464d4f3%28v=vs.90%29.aspx

Take a look at MAKEWPARAM (http://msdn.microsoft.com/en-us/library/windows/desktop/ms632664(v=vs.85).aspx) and MAKELPARAM.

Related

Where are the rest of the TMessage missing params?

The VCL TMessage class provides the Message, WParam and LParam members, but a window message has more members:
typedef struct tagMSG {
HWND hwnd;
UINT message;
WPARAM wParam;
LPARAM lParam;
DWORD time;
POINT pt;
DWORD lPrivate;
} MSG, *PMSG, *NPMSG, *LPMSG;
Where are the hwnd, time, pt and lPrivate members? I'm in specially need of the time parameter.
Is there a way to access the original message that TMessage is constructed from (or any other means to get the time parameter)?
I'm handling my messages in TComponent::WndProc(Winapi::Messages::TMessage &Message).
Where are the hwnd, time, pt and lPrivate members?
There aren't any such members in TMessage.
MSG is the structure that the Win32 API uses in a message loop to retrieve messages from a message queue, via the GetMessage() and PeekMessage() functions, prior to dispatching them to window procedures via DispatchMessage(). The time, pt, and lPrivate values are not delivered to a window procedure, however a window procedure can retrieve the time and pt values via the GetMessageTime() and GetMessagePos() functions, respectively (the lPrivate value is not accessible).
TMessage is the structure that the VCL uses in window procedures that are created by the RTL's MakeObjectInstance() function. This function allows classes, like the VCL's TWinControl and TTimer, to use non-static virtual WndProc() methods as Win32 window procedures.
In a standard Win32 window procedure, there are only 4 parameters available - hWnd, uMsg, wParam and lParam. An RTL-based window procedure ignores the hWnd (as it already knows exactly which object method to call), copies the uMsg, wParam and lParam values into a TMessage, calls the target WndProc() method passing it the TMessage, and then returns the TMessage::Result value back to the OS.
I'm in specially need of the time parameter. Is there a way to access the original message that TMessage is constructed from (or any other means to get the time parameter)?
If the message comes from the message queue of the thread that is calling your WndProc(), you can use the Win32 API GetMessageTime() function. Or, you can use the Win32 API SetWindowsHookEx() function to install a WH_GETMESSAGE hook into the thread's message queue.
If your component's WndProc() is called in the main UI thread specifically, you can alternatively use the VCL's TApplication::OnMessage or TApplicationEvents::OnMessage events, which receive a copy of the original MSG structure. Your component can use a private TApplicationEvents object to hook the OnMessage event.
However, a window procedure can receive both queued messages and non-queued messages, so if the message does not come from the calling thread's message queue at all, then there is simply no time (or pt) value available to retrieve for it, as non-queued messages do not go through the MSG structure to begin with.
I'm handling my messages in TComponent::WndProc(Winapi::Messages::TMessage &Message).
TComponent does not have a WndProc() method. Perhaps you are thinking of TWinControl::WndProc() instead?

Windows API: find process for a file mapping handle

I created an SSH agent (similar to PuTTY's pageant.exe) which has a predefined protocol: Authentication requests are sent to the agent window via WM_COPYDATA containing the name of a file mapping:
// mapname is supplied via WM_COPYDATA
HANDLE filemap = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, mapname);
Is it possible to find out which process (ultimatively, the process name) created a particular file mapping?
I can use GetSecurityInfo on "filemap" to get the security attributes (SID, GID, ...) but how to I get the process itself?
Important note: It is NOT possible to change the protocol (e.g. add information about the sender to WM_COPYDATA) because this is the predefined protocol used by all PuTTY-like applications!
Don't try to find the process by file handle, it's complicated you need to enumerate process to find open handles for each. The WM_COPYDATA message send you the handle of the sender window, a call to GetWindowThreadProcessId should give your answer. Keep in mind that WM_COPYDATA is a way to communicate between 32 and 64 bits process so your process maybe in different space than the caller.
Edit-->
You receive the sender HWND in the WM_COPYDATA you only have to use that HWND to get the process ID
switch (uiMsg)
{
case WM_COPYDATA:
{
DWORD theProcessID;
GetWindowThreadProcessId((HWND) wParam, &theProcessID);
COPYDATASTRUCT *pMyCDS = (PCOPYDATASTRUCT) lParam;
/*...*/
}
/*...*/
}

How to design cleaner PostMessage chain in WinApi/MFC

I have a MFC GUI app that has multiple frames (sort of like Outlook'ish behavior with main window, and message/appointment windows being created in new frames, or Skype like multi frame syncronization), and I need to PostMessage malloc'ed data through the window hierarchy.
Say, I get the string, _wcsdup it, PostMessage(WM_NEWSTRING, ...), and, the control somewhere deep down the hierarchy processes it, or if there are no subscribers, the message get's cleaned.
What I am looking into now, is that all messages are posted to application thread, thread finds the active frame or best fit frame, passes the message to it, frame passes the message to it's view, the view passes message to subview and so on, if there is no view to process the message, it get's free'd.
The problem is that these chaining commands are pretty tiring to write, as I have to duplicate the message forwarding code in each CWnd class I have. At the same time, resource cleanup is pretty unpleasant, because if there is no window to catch the message, someone has to call the free. Therefore simply posting the message to the main message pump without extra handling, hoping that someone will always catch it, is not a valid approach. PostMessage returns S_OK, no one sees the message as processable, and it's left dangling.
Is there a better, correct approach for what I'm looking for?
I would never use PostMessage as you describe. My solution often involves a hand-shake:
// From CNotifierBlah
PostMesssage(hWnd, UWM_NEW_DATA, 0, 0);
//
LRESULT CDestinationWnd::OnNewData(WPARAM wParam, LPARAM lParam)
{
CNewData newData = GetNotifierBlah().GetNewData(); // Thread-safe getter!
}
Pretty much the same as Observer pattern.

Using the Windows SetTimer() function

I am getting confused with the SetTimer() function.
SetTimer() takes three parameters:
SetTimer(1,2000,Timerflow);
However I've seen another version of SetTimer that takes four parameters:
SetTimer(NULL,1,2000,Timerflow);
What is the difference between these two functions?
I know SetTimer() Three parameters. But when I try the four parameter SetTimer() function, I get the error:
error C2660: 'SetTimer' : function does not take 4 parameters
So what is the main difference and what causes this error?
The 4-parameter version is the plain Win32 API version, and the first parameter is a window handle.
The 3-parameter version is a member of MFC's CWnd class, and works with the window handle of the CWnd instance for which you call it.
If you need to call the 4-parameter Win32 API from within a method of a CWnd-derived object, do this:
::SetTimer(NULL, 1, 2000, Timerflow);
The only Windows API called SetTimer takes four parameters. Presumably the other one is part of MFC or some other framework, and the first parameter is implied by the object you call it on. For example:
CWnd * w = .... // get window somehow
w->SetTimer(1,2000,Timerflow);
If you use SetTimer to create a timer in GUI classes such as the MFC's CWnd, you can use the 3-parameter form:
UINT SetTimer(
UINT nIDEvent, // timer identifier
UINT uElapse, // time-out value
TIMERPROC lpTimerFunc // address of timer procedure
);
But if you use it in non-GUI classes, you have to use the 4-parameter form. The first parameter is to specify which GUI component will respond for the timer event. This version of the function is called from Win32 API.
eUINT SetTimer(
HWND hWnd, // handle of window for timer messages
UINT nIDEvent, // timer identifier
UINT uElapse, // time-out value
TIMERPROC lpTimerFunc // address of timer procedure
);
It is very simple, isn't it?
According to MSDN: https://msdn.microsoft.com/en-us/library/windows/desktop/ms644906(v=vs.85).aspx, the first and last parameters are optional. Therefore, you can have a SetTimer call with even 2 parameters (not recommended however). The error is most likely from an incorrect cast (needs a uint_ptr, you give an hwnd, for example)

How to correctly use SetWindowsHookEx & CallNextHookEx

I can correctly setup up a windows hook, but I get confused by the line in MSDN that says "Calling the CallNextHookEx function to chain to the next hook procedure is optional, but it is highly recommended; otherwise, other applications that have installed hooks will not receive hook notifications and may behave incorrectly as a result. You should call CallNextHookEx unless you absolutely need to prevent the notification from being seen by other applications.".
I want to be a good programming citizen and call the next hook. But, my hook procedure looks like this:
LRESULT CALLBACK CBTProc(int code, WPARAM wp, LPARAM lp)
{
if (code != HCBT_CREATEWND)
{
// What do I do here? It's not the event I requested so how do I pass it on?
return 0;
}
// It's the code we want (create window)
CallNextHookEx(...);
...
}
So, what happens in the hook procedure if the code isn't the one I'm interested in? How do I call the next hook?
Edit: The main problem is that a HHOOK is returned from the SetWindowsHookEx, and that needs to be passed to the CallNextHookEx function.
Update: It seems the hook parameter is ignored on the NT platforms:
http://msdn.microsoft.com/en-us/library/ms644974.aspx
http://www.klenotic.com/pl/null_hhook/
According to the docs, the proper thing to do is pass the arguments you received directly to CallNextHookEx, exactly as you received them. You should also call CallNextHookEx regardless of whether you decided to handle the hook message.
According to MSDN, the first parameter to CallNextHookEx is ignored on on NT/XP/2003, and for older Win95-based operating systems it should be the HHOOK you received when you registered your hook with SetWindowsHookEx. The docs don't specify a value for Windows 2000, but since it's part of the NT family, a reasonable guess is that it's ignored there as well.
Given all that, a good way to code the method for NT-family operating systems might be this:
LRESULT CALLBACK CBTProc( int code, WPARAM wp, LPARAM lp )
{
if( code == HCBT_CREATEWND )
ProcessCreateWnd( wp, lp );
return CallNextHookEx( 0, code, wp, lp );
}
void ProcessCreateWnd( WPARAM wp, LPARAM lp )
{
// my code here
}
This makes sure that you always call the hook at the end of your processing, and makes it hard to accidentally add a return that will bypass CallNextHookEx.

Resources