冰楓論壇
標題:
[C#] 透過行程名稱/行程ID操作程式程式
[打印本頁]
作者:
whitefox
時間:
2023-6-2 21:00
標題:
[C#] 透過行程名稱/行程ID操作程式程式
判斷程式是否執行
public bool IsWindowExist(IntPtr handle)
{
return (!(GetWindow(new HandleRef(this, handle), 4) != IntPtr.Zero) && IsWindowVisible(new HandleRef(this, handle)));
}
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetWindow(HandleRef hWnd, int uCmd);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
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);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool EnumWindows(EnumThreadWindowsCallback callback, IntPtr extraData);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
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;
[DllImport("User32.dll", EntryPoint = "SendMessage")]
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();
複製代碼
歡迎光臨 冰楓論壇 (https://bingfong.com/)
Powered by 冰楓