如何在C#中隐藏/取消隐藏进程?

我试图在Visual C#2010 – Windows窗体应用程序中启动外部进程。 目标是将该过程作为隐藏窗口启动,并在以后取消隐藏窗口。

我已经更新了我的进度:

//Initialization [DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hwnd, int nCmdShow); [DllImport("user32.dll")] private static extern bool EnableWindow(IntPtr hwnd, bool enable); [DllImport("user32.dll")] private static extern bool MoveWindow(IntPtr handle, int x, int y, int width, int height, bool redraw); SW_SHOW = 5; 

以下内容放在我的主要function中:

 ProcessStartInfo info = new ProcessStartInfo("process.exe"); info.WindowStyle = ProcessWindowStyle.Hidden; Process p = Process.Start(info); p.WaitForInputIdle(); IntPtr HWND = p.MainWindowHandle; System.Threading.Thread.Sleep(1000); ShowWindow(HWND, SW_SHOW); EnableWindow(HWND, true); MoveWindow(HWND, 0, 0, 640, 480, true); 

但是,因为窗口是以“隐藏” p.MainWindowHandle = 0p.MainWindowHandle = 0 。 我无法成功显示窗口​​。 我也试过HWND = p.Handle没有成功。

有没有办法为我的窗户提供新的手柄? 这可能会解决我的问题。

参考文献:

MSDN ShowWindow

MSDN论坛

如何导入.dll

最后,该过程正常运行。 感谢您的帮助,我想出了这个解决方案。

p.MainWindowHandle为0,所以我不得不使用user32 FindWindow()函数来获取窗口句柄。

 //Initialization int SW_SHOW = 5; [DllImport("user32.dll",SetLastError=true)] private static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hwnd, WindowShowStyle nCmdShow); [DllImport("user32.dll")] private static extern bool EnableWindow(IntPtr hwnd, bool enabled); 

在我的主要function:

 ProcessStartInfo info = new ProcessStartInfo(); info.FileName = "notepad"; info.UseShellExecute = true; info.WindowStyle = ProcessWindowStyle.Hidden; Process p = Process.Start(info); p.WaitForInputIdle(); IntPtr HWND = FindWindow(null, "Untitled - Notepad"); System.Threading.Thread.Sleep(1000); ShowWindow(HWND, SW_SHOW); EnableWindow(HWND, true); 

参考文献:

pinvoke.net:FindWindow()

取消隐藏窗口的示例代码:

 int hWnd; Process[] processRunning = Process.GetProcesses(); foreach (Process pr in processRunning) { if (pr.ProcessName == "notepad") { hWnd = pr.MainWindowHandle.ToInt32(); ShowWindow(hWnd, SW_HIDE); } } 

文档详细说明要使用ProcessWindowStyle.Hidden还必须将ProcessStartInfo.UseShellExecute设置为false。 http://msdn.microsoft.com/en-us/library/system.diagnostics.processwindowstyle.aspx

您必须以某种方式知道窗口句柄以便以后取消隐藏它。