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

时间:2012-04-30 17:03:32

标签: c# visual-studio-2010 process

我正在尝试在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;

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

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 = 0启动的。我无法成功显示窗口​​。我也试过HWND = p.Handle但没有成功。

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

参考文献:

MSDN ShowWindow

MSDN Forums

How to Import .dll

3 个答案:

答案 0 :(得分:11)

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

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, int nCmdShow);

[DllImport("user32.dll")]
private static extern bool EnableWindow(IntPtr hwnd, bool enabled);

在我的主要功能中:

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

编辑: 从dllImport声明中删除了WindowShowStyle:您可以将其定义为int。我定义了一个名为WindowShowStyle的枚举来定义this article中概述的常量。它更适合我的编码模式,以定义枚举,而不是使用常量或硬编码值。

答案 1 :(得分:2)

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

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

答案 2 :(得分:1)

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

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