这是我的问题:我需要从 C# 程序关闭一个已经运行的进程。
问题是该进程现在作为图标运行(最小化到任务栏),除非用户至少打开它一次(这在无人值守的计算机上永远不会发生),否则它永远不会
有一个主窗口。
我的另一个要求是应用程序是closed not killed。我需要它将它的内存缓冲区写入磁盘 - 杀死它会导致数据丢失。
到目前为止,这是我尝试过的:
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条款,发现后主窗口句柄 == 0当窗口最小化时。删除if没有帮助。既没有关闭主窗口()也不Close()工作。这Kill()确实如此,但如上所述 - 这不是我需要的。
任何想法都会被接受,包括使用神秘的 Win32 API 函数:)
这应该有效:
[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 位。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)