I am trying to send WM_CLOSE
from my app to a target app to tell it to close. I am running in the VS debugger on NET 6.0.
I find the handle of the target app and send a WM_CLOSE
message to its handle, but Spy says that the message never arrives at the target window, and so of course the target window does not close.
I know I have the right target handle because I can see it in Spy (I tag the target window title bar manually with the Spy crosshairs), and they match. Also when I get the window title from the handle, it gives the same window title visible in the title bar of the target app. And the return code from the PostMessage
call is zero, so PostMessage
is saying that it sent the message.
But neither PostMessage
nor SendMessage
sends a message that is visible in the messages for the target window that are being logged in real-time in the Spy rolling display.
Why is my WM_CLOSE
message not: (1) visible in Spy , and (2) not reaching the target app?
public static void
SendCloseToHandle(IntPtr handle) {
var result = PostMessage(handle, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
if (result != 0) {
FormAppendTextContent($"WM_CLOSE failed to send. {result:X}");
return;
}
//SendMessage(handle, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
var title = GetWindowTitle(handle);
FormAppendTextContent($"Posted WM_CLOSE message to {title} '{handle:X}'");
}
CodePudding user response:
And the return code from the PostMessage call is zero, so PostMessage is saying that it sent the message.
That's just wrong. The PostMessage
function returns zero on failure. So, assuming your code (as presented) doesn't show the error message, then the PostMessage
call is failing, and WM_CLOSE
isn't being sent to the target.
You need to change your error-handling to use if (result == 0) { ...
and then, in that block, call the GetLastError
function to retrieve the error code. If that is 5
(as I suspect), then the call is failing due to incorrect UIPI access, and you will need to address that issue as described in this Q/A: Cross-process PostMessage, UIPI restrictions and UIAccess=”true”.