5

我正在尝试在 Visual C# 2010 - Windows Forms 应用程序中启动一个外部进程。目标是将进程作为隐藏窗口启动,并在以后取消隐藏该窗口。

我更新了我的进度:

//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 展示窗口

MSDN 论坛

如何导入 .dll

4

3 回答 3

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 的枚举来定义本文中概述的常量。定义枚举而不是使用常量或硬编码值更适合我的编码模式。

于 2012-05-01T15:44:54.017 回答
2

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

int hWnd;
Process[] processRunning = Process.GetProcesses();
foreach (Process pr in processRunning)
{
    if (pr.ProcessName == "notepad")
    {
        hWnd = pr.MainWindowHandle.ToInt32();
        ShowWindow(hWnd, SW_HIDE);
    }
}
于 2012-04-30T17:31:21.780 回答
1

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

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

于 2012-04-30T17:15:29.753 回答