Jon Cage
Jon Cage

Reputation: 37518

How do I gracefully close another application?

I have a C++/CLI based install application which needs to close another app I've written, replace the application's .exe and dlls and the re-run the executable.

First of all I need to close that window along the following lines:

HWND hwnd = FindWindow(NULL, windowTitle);
if( hwnd != NULL )
{
    ::SendMessage(hwnd, (int)0x????, 0, NULL);
}

I.e. find a matching window title (which works) ...but then what message do I need send the remote window to ask it to close?

...or is there a more .net-ish way of donig this without resorting to the windows API directlry?

Bare in mind that I'm limited to .net 2.0

Upvotes: 5

Views: 4676

Answers (5)

Michael Baldry
Michael Baldry

Reputation: 2028

UPDATE

Use WM_CLOSE. I was wrong.

Upvotes: -1

Brian
Brian

Reputation: 25834

You can call WM_CLOSE using SendMessage.

[DllImport("User32.dll", EntryPoint = "SendMessage")]
public static extern int SendMessage(int hWnd, int Msg, int wParam, ref COPYDATASTRUCT lParam);

See http://boycook.wordpress.com/2008/07/29/c-win32-messaging-with-sendmessage-and-wm_copydata/ for code sample.

Upvotes: 3

Adrian McCarthy
Adrian McCarthy

Reputation: 48019

Guidelines from MSDN

  1. Send WM_QUERYENDSESSION with the lParam set to ENDSESSION_CLOSEAPP.
  2. Then send WM_ENDSESSION with the same lParam.
  3. If that doesn't work, send WM_CLOSE.

Upvotes: 2

Jon Cage
Jon Cage

Reputation: 37518

In case anyone wants to follow the more .net-ish way of donig things, you can do the following:

using namespace System::Diagnostics;

array<Process^>^ processes = Process::GetProcessesByName("YourProcessName");
for each(Process^ process in processes)
{
    process->CloseMainWindow(); // For Gui apps
    process->Close(); // For Non-gui apps
}

Upvotes: 1

Andreas Rejbrand
Andreas Rejbrand

Reputation: 109003

WM_CLOSE?

Upvotes: 5

Related Questions