whitefox 發表於 2023-6-2 21:00:07

[C#] 透過行程名稱/行程ID操作程式程式

判斷程式是否執行public bool IsWindowExist(IntPtr handle)
{
    return (!(GetWindow(new HandleRef(this, handle), 4) != IntPtr.Zero) && IsWindowVisible(new HandleRef(this, handle)));
}


public static extern IntPtr GetWindow(HandleRef hWnd, int uCmd);


public static extern bool IsWindowVisible(HandleRef hWnd);根據處理緒Handle查找程式public IntPtr GetWindowHandle(int processId)
{
    var windowHandle = IntPtr.Zero;
    EnumThreadWindowsCallback windowsCallback = new EnumThreadWindowsCallback(FindMainWindow);
    EnumWindows(windowsCallback, IntPtr.Zero);

    GC.KeepAlive(windowsCallback);

    bool FindMainWindow(IntPtr handle, IntPtr extraParameter)
    {
        int num;
        GetWindowThreadProcessId(new HandleRef(this, handle), out num);
        if (num == processId && IsWindowExist(handle))
        {
            windowHandle = handle;
            return true;
        }
        return false;
    }

    return windowHandle;
}

public delegate bool EnumThreadWindowsCallback(IntPtr hWnd, IntPtr lParam);


public static extern bool EnumWindows(EnumThreadWindowsCallback callback, IntPtr extraData);


public static extern int GetWindowThreadProcessId(HandleRef handle, out int processId);根據行程ID關閉程式public void CloseWindow(int processId)
{
    var mwh = GetWindowHandle(processId);
    SendMessage(mwh, MW_CLOSE, 0, 0);
}
const int MW_CLOSE = 0x0010;


public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);關閉所有此行程名稱的程式public void CloseAllWindows(string processName)
{
    Process[] processList = Process.GetProcessesByName(processName);
    foreach (Process process in processList)
    {
        CloseMainWindow(process.Id);
    }
}直接關閉所有行程public static bool CloseAllProcesses(string processName)
{
    try
    {
        Process[] psEaiNotes = Process.GetProcessesByName(processName);
        foreach (Process psEaiNote in psEaiNotes)
        {
            psEaiNote.Kill();
        }
    }
    catch
    {
        return false;
    }
    return true;
}重新啟動程序string appFileName = currentClientProcess.MainModule.FileName;

Process newClient = new Process();
newClient.StartInfo.FileName = appFileName;
// 設定執行程序的開始目錄
newClient.StartInfo.WorkingDirectory = System.Windows.Forms.Application.ExecutablePath;

// 執行程序
currentClientProcess.Kill();
newClient.Start();
頁: [1]
查看完整版本: [C#] 透過行程名稱/行程ID操作程式程式