C# 通过进程名/进程Id 操作窗口/程序

时间:2023-03-09 15:33:17
C# 通过进程名/进程Id 操作窗口/程序

1. 判断窗口是否存在

     private bool IsWindowExist(IntPtr handle)
{
return (!(GetWindow(new HandleRef(this, handle), ) != 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);

2. 获取窗口句柄

     /// <summary>
/// 获取应用程序窗口句柄
/// </summary>
/// <param name="processId"></param>
/// <returns></returns>
private 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);

3. 关闭应用窗口

根据进程Id关闭应用窗口:

     /// <summary>
/// 关闭程序主窗口
/// </summary>
/// <param name="processId">进程ID</param>
public void CloseWindow(int processId)
{
var mwh = GetWindowHandle(processId);
SendMessage(mwh, MW_CLOSE, , );
}
const int MW_CLOSE = 0x0010; [DllImport("User32.dll", EntryPoint = "SendMessage")]
private 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);
}
}

当然,直接杀进程,是最快的方法:

     /// <summary>
/// 关闭所有进程
/// </summary>
/// <param name="processName"></param>
/// <returns></returns>
public static bool CloseAllProcesses(string processName)
{
try
{
Process[] psEaiNotes = Process.GetProcessesByName(processName);
foreach (Process psEaiNote in psEaiNotes)
{
psEaiNote.Kill();
}
}
catch
{
return false;
} return true;
}

4. 重启程序

     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();

窗口之间发送/接收消息的处理,请参考《C# 跨进程通信