C#Process.MainWindowHandle总是返回IntPtr的零

问题描述:

这是我的代码:C#Process.MainWindowHandle总是返回IntPtr的零

  using (Process game = Process.Start(new ProcessStartInfo() { 
     FileName="DatabaseCheck.exe", 
     RedirectStandardOutput = true, 
     CreateNoWindow = true, 
     UseShellExecute = false })) 
     { 
      lblLoad.Text = "Loading"; 
      int Switch = 0; 

      while (game.MainWindowHandle == IntPtr.Zero) 
      { 
       Switch++; 
       if (Switch % 1000 == 0) 
       { 
        lblLoad.Text += "."; 
        if (lblLoad.Text.Contains("....")) 
         lblLoad.Text = "Loading."; 

        lblLoad.Update(); 
        game.Refresh(); 
       } 
      } 

问题是,game.MainWindowHandle总是IntPtr.Zero。我需要找到RAN过程的IntPtr的确认,该游戏是由启动器启动的,所以我做游戏送它的IntPtr,让发射器响应,如果它的好。但为此,我必须专门知道运行过程的IntPtr。

在此先感谢!

主窗口是通过当前具有焦点(顶层形式)的过程中打开窗口。您必须使用Refresh方法来刷新进程对象得到当前主窗口句柄,如果它已经改变了

你可以得到MainWindowHandle属性仅适用于在本地计算机上运行的进程。 MainWindowHandle属性是唯一标识与该进程关联的窗口的值。

的方法具有与之相关联的主窗口仅当处理具有图形界面。如果关联的进程没有主窗口,则MainWindowHandle值为零。对于隐藏的进程,该值也为零,即在任务栏中不可见的进程。这对于作为图标出现在通知区域,在任务栏最右侧的进程情况。

如果您刚刚启动了一个进程并希望使用其主窗口句柄,请考虑使用WaitForInputIdle方法来允许进程完成启动,以确保已创建主窗口句柄。否则,将抛出异常。

+0

会尝试,当我回家。谢谢 – Kfirprods 2013-04-24 09:15:59

+0

谢谢,它的工作。 – Kfirprods 2013-04-24 12:00:54

+0

注意,在4.5这个不再需要(传闻 - 我的代码工作在4.5和直到我说'.REFRESH()'当我下降到3.5失败) – Basic 2014-03-11 09:49:32

while (!proc.HasExited) 
{ 
    proc.Refresh(); 
    if (proc.MainWindowHandle.ToInt32() != 0) 
    { 
     return proc.MainWindowHandle; 
    } 
} 
+1

嗨,您的帖子已被标记为“低素质”,可能是因为它只包含代码。你可以通过提供解释这个问题的答案和原因的解释来大幅提高你的答案。 – Ben 2013-09-27 08:07:26

一种解决方法是通过所有顶层窗口枚举,直到你找到一个匹配检查自己的进程ID ...


    [DllImport("user32.dll")] 
    public static extern IntPtr FindWindowEx(IntPtr parentWindow, IntPtr previousChildWindow, string windowClass, string windowTitle); 

    [DllImport("user32.dll")] 
    private static extern IntPtr GetWindowThreadProcessId(IntPtr window, out int process); 

    private IntPtr[] GetProcessWindows(int process) { 
     IntPtr[] apRet = (new IntPtr[256]); 
     int iCount = 0; 
     IntPtr pLast = IntPtr.Zero; 
     do { 
      pLast = FindWindowEx(IntPtr.Zero, pLast, null, null); 
      int iProcess_; 
      GetWindowThreadProcessId(pLast, out iProcess_); 
      if(iProcess_ == process) apRet[iCount++] = pLast; 
     } while(pLast != IntPtr.Zero); 
     System.Array.Resize(ref apRet, iCount); 
     return apRet; 
    }