I have an application that I would like to close from my current C# application. The problem is that the application I want to close has an exit confirmation that requires the user to confirm the closing of the application.
When I use this code:
foreach (Process process in runningProcesses)
{
if (process.ProcessName == "ProcessName")
process.CloseMainWindow();
}
the exit confirmation popup still appears on the other application.
When questions similar to this are asked elsewhere, all I can find are people suggesting process.Kill() to get past the exit confirmation. This is not an option for me as I need the other application to close down gently.
Is there a way to send a closing message to the other application that will force it to start its shutdown process without killing the process abruptly?
CodePudding user response:
If you have to close the application gently and it displays a confirmation when trying to close it, then you'll have to handle it as well.
The actual way to do that depends on what exactly the popup is. If it's a standard dialog, something like the following could suffice:
SendMessage(hDlg, WM_COMMAND, IDOK, 0);
If it's a less standard dialog, but still using standard Windows components (like MFC or WinForms or something), you'll have to inspect its window structure (using Spy for example), get the handle of the button you need to press and use something like:
SendMessage(hBtn, BM_CLICK, 0, 0);
If however the dialog doesn't use standard windows (like Qt or WPF), you'll need a lot more specialized code. I'd suggest hooking into the parent dialog and pressing the button yourself to see what events are triggered (Spy can do that) and mimicking them with SendMessage
.
CodePudding user response:
You can send a WM_ENDSESSION
message, which in most applications cause all forms to gracefully close.
PostMessage(process.MainWindowHandle, WM_ENDSESSION, IntPtr.Zero, new IntPtr(ENDSESSION_CLOSEAPP));
Definitions:
[DllImport("user32.dll")]
public static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
const int WM_ENDSESSION = 0x16;
const int ENDSESSION_CLOSEAPP = 0x1;