【问题标题】:IntPtr always Zero C#IntPtr 始终为零 C#
【发布时间】:2016-06-15 14:43:04
【问题描述】:

我正在启动 Internet Explorer 进程。问题是它在 p.MainWindowHandle 中总是返回零。 我的目标是获取 mainwindowHandler 并最小化刚刚启动的特定窗口。相同的代码适用于 chrome 浏览器。但在 Internet Explorer 中它不起作用。 我的代码如下。

Process p = Process.Start("IEXPLORE.EXE", "www.google.com");
ShowWindow(p.MainWindowHandle, 2);

ShowWindow 是一个调整窗口大小的方法。

【问题讨论】:

  • 复制stackoverflow.com/questions/16185217/…快捷方式:在查看MainWindowHandle之前调用Refresh()方法
  • 如果要创建具有最小化窗口的进程,更好的方法是使用ProcessStartInfo.WindowStyle。事实上,MSDN 示例恰好使用了iexplore.exe
  • 我已经调用了刷新方法,但问题仍然存在。
  • p.Refresh(); IntPtr ptr = p.MainWindowHandle;
  • 浏览器初始化和创建窗口当然需要时间。您至少必须使用 p.WaitForInputIdle()。但这还不够,您必须循环直到获得非零值。每次尝试后都睡一会儿,不要永远循环。

标签: c#


【解决方案1】:

在许多其他原因中(请参阅问题的 cmets),您必须等待 进程才能创建 主窗口:

  // Process is IDisposable, wrap it into using
  using (Process p = Process.Start("IEXPLORE.EXE", "www.google.com")) {
    ...
    // wait till the process creates the main window
    p.WaitForInputIdle();

    // Main window (if any) has been created, so we can ask for its handle
    ShowWindow(p.MainWindowHandle, 2);
  }

【讨论】:

  • 但真的,不要这样做。从来没有充分的理由强制用户使用特定的浏览器。让用户控制他/她的默认浏览器。只需使用带有 URL 的 Process.Start。
  • 实际上我必须强制用户在 Internet Explorer 中打开 url
猜你喜欢
  • 2016-05-02
  • 2012-01-16
  • 2020-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多