Robin
Robin

Reputation: 451

SendMessage to close hidden window

I'm trying to close a hidden window program by sendMessage but it does not work because the mainwindowhandle is zero. I tried the other handle but it does not work too

Process p = new Process ();
p.StartupInfo.FileName = "HiddenWindowWithMessagePump.exe"
p.Start ();

[DllImport ("user32.dll")]
static extern IntPtr SendMessage (IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

 // I tried both WM_CLOSE and WM_QUIT
 const int WM_CLOSE    = 0x0010;
 const int WM_QUIT     = 0x12;

 // p.MainWindowHandle is 0
 SendMessage (p.MainWindowHandle,    WM_QUIT, IntPtr.Zero, IntPtr.Zero);
 // does not work
 SendMessage (p.Handle,             WM_QUIT, IntPtr.Zero, IntPtr.Zero);

 // this is different from p.Handle, but does not work too
 IntPtr p2 = System.Diagnostics.Process.GetProcessById (p.Id).Handle;

The hidden window program has a message pump

 CreateWindowEx (NULL,L"X",    // name of the window class
                      L"X",   // title of the window
                      0,
                      300,    // x-position of the window
                      300,    // y-position of the window
                      500,    // width of the window
                      400,    // height of the window
                      HWND_MESSAGE,
                      NULL,         // we aren't using menus, NULL
                      hInstance,        // application handle
                      NULL);            // used with multiple windows, NULL

    while (true)
    {
        if (PeekMessage (&msg, 0, 0, 0, PM_REMOVE))
        {
            if (WM_QUIT == msg.message)
                break;

            TranslateMessage (&msg);
            DispatchMessage (&msg);
        }
    }

Upvotes: 1

Views: 2775

Answers (1)

Gowri Pranith Kumar
Gowri Pranith Kumar

Reputation: 1685

You can try finding the window if you dont have the handle . try using the below code

[DllImport("user32.dll")]
public static extern int FindWindow(string lpClassName,string lpWindowName);

int iHandle = FindWindow("Notepad", "Untitled - Notepad");    
if (iHandle > 0)
{
    SendMessage(iHandle, WM_SYSCOMMAND, SC_CLOSE, 0);
}  

Upvotes: 4

Related Questions