简体   繁体   中英

WM_CLOSE is not arriving at the target window; Spy++ cannot see WM_CLOSE either

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}'");
  }

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” .


Note: Calling the GetLastError WinAPI function from C# and/or .Net projects is not trivial; for an in-depth discussion of how to properly do so, see here: WinApi - GetLastError vs. Marshal.GetLastWin32Error .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM