我正在尝试在 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
但没有成功。
有没有办法为我的窗口提供一个新句柄?这可能会解决我的问题。
引用资料:
最佳答案
最后,进程运行正常。感谢大家的帮助,我想出了这个修复方法。
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);
引用资料:
编辑: 从 dllImport 声明中删除了 WindowShowStyle:您可以将其定义为 int。我定义了一个名为 WindowShowStyle 的枚举来定义 this article 中概述的常量.定义枚举而不是使用常量或硬编码值更符合我的编码模式。
关于c# - 如何在 C# 中隐藏/取消隐藏进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10387586/