Closing a minimized / designated process with C #

Here is my problem: I need to close a process already running from a C # program. The problem is that the process now works like an icon (it comes down to the taskbar), and if the user does not open it at least once (which will never happen on machines without supervision), it will never have a main window.

Another requirement that I have is that the application is closed, not killed . I need it to write memory buffers to disk - and their destruction leads to data loss.

Here is what I have tried so far:

        foreach (Process proc in Process.GetProcesses())
        {
            if (proc.ProcessName.ToLower().StartsWith("myapp"))
            {
                if (proc.MainWindowHandle.ToInt32() != 0)
                {
                    proc.CloseMainWindow();
                    proc.Close();
                    //proc.Kill();  <--- not good!
                }
            }
        }

if , MainWindowHandle == 0, . , . CloseMainWindow(), () . (), , , , .

, Win32 API:)

+3
4

:

rpetrich: , , , , - exe . , , . , , MainWindowHandle 0.

: , - . PostQuitMessage. , , , .

Craig: : , , , , . , - "exit".

script/ . ( exe ), . , , API, ( ), .

, , script , .

, , , !

0

:

[DllImport("user32.dll", CharSet=CharSet.Auto)]
private static extern IntPtr FindWindow(string className, string windowName);
[DllImport("user32.dll", CharSet=CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

private const int WM_CLOSE = 0x10;
private const int WM_QUIT = 0x12;

public void SearchAndDestroy(string windowName) 
{
    IntPtr hWnd = FindWindow(null, windowName);
    if (hWnd == IntPtr.Zero)
        throw new Exception("Couldn't find window!");
    SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}

WM_CLOSE, WM_QUIT. 32-, 64-.

+2

. , ( SysTray)? .

Win32 " ", ( - , PostQuitMessage WM_DESTROY, ).

Spy ++. , , Spy → Processes . . , . , . . FindWindow ( EnumWindows) .

WM_CLOSE WM_SYSCOMMAND/SC_CLOSE ( "X" ). .

, Win32 . , P/Invoke , .NET-.

+1

The question is to find out why you are trying to do this: If the only user interface in the process is the system tray icon, why do you want to kill it, but leave the process running? How will the user access the process? And if the machine is “unattended”, why bother with the tray icon?

-1
source

Source: https://habr.com/ru/post/1697285/


All Articles