2012-11-05 88 views
1

我想获得一个窗口标题被间谍++(以红色突出显示)给出如何获得窗口标题?

enter image description here

我有代码来获取窗口标题。它通过调用GetWindowText来检查窗口标题,通过枚举所有窗口来完成此操作。如果窗口的标题= "window title | my application"是开放的,那么我希望窗口标题包含在枚举中并发现。

如果窗口计数不是1,那么函数将释放任何窗口句柄并返回null。在返回null的情况下,这被认为是失败。在我跑这个代码100次一个测试用例我有99

public delegate bool EnumDelegate(IntPtr hWnd, int lParam); 

     [DllImport("user32.dll")] 
     [return: MarshalAs(UnmanagedType.Bool)] 
     static extern bool IsWindowVisible(IntPtr hWnd); 

     [DllImport("user32.dll", EntryPoint = "GetWindowText", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)] 
     static extern int GetWindowText(IntPtr hWnd, StringBuilder lpWindowText, int nMaxCount); 

     [DllImport("user32.dll", EntryPoint = "EnumDesktopWindows", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)] 
     static extern bool EnumDesktopWindows(IntPtr hDesktop, EnumDelegate lpEnumCallbackFunction, IntPtr lParam); 

     static List<NativeWindow> collection = new List<NativeWindow>(); 

public static NativeWindow GetAppNativeMainWindow() 
     {    
      GetNativeWindowHelper.EnumDelegate filter = delegate(IntPtr hWnd, int lParam) 
      { 
       StringBuilder strbTitle = new StringBuilder(255); 
       int nLength = GetNativeWindowHelper.GetWindowText(hWnd, strbTitle, strbTitle.Capacity + 1); 
       string strTitle = strbTitle.ToString(); 

       if (!string.IsNullOrEmpty(strTitle)) 
       { 
        if (strTitle.ToLower().StartsWith("window title | my application")) 
        { 
         NativeWindow window = new NativeWindow(); 
         window.AssignHandle(hWnd); 
         collection.Add(window); 
         return false;//stop enumerating 
        } 
       } 
       return true;//continue enumerating 
      }; 

      GetNativeWindowHelper.EnumDesktopWindows(IntPtr.Zero, filter, IntPtr.Zero); 
      if (collection.Count != 1) 
      { 
       //log error 

       ReleaseWindow(); 
       return null; 
      }      
      else 
       return collection[0]; 
     } 

     public static void ReleaseWindow() 
     { 
      foreach (var item in collection) 
      { 
       item.ReleaseHandle(); 
      } 
     } 

注意,我流的"strTitle"所有值到一个文件中的失败计数。然后在我的标题中对关键字进行了文本基础搜索,结果不成功。为什么枚举在某些情况下找不到我正在寻找的窗口,但在其他情况下却可以找到它?

+0

您对错误/意外行为“工作非常糟糕”有非常非描述性的解释......考虑添加细节。 –

回答

2

你是如何运行它100次的?在紧密的循环中,重新启动应用程序等?

根据你的代码,如果你在一个循环中运行它而没有清除集合,那么你会在找到的第一个条目后发现错误,因为错误条件if (collection.Count != 1)

然后在每个EnumDesktopWindows调用你只需添加到集合,然后返回给调用者。该集合永远不会被清除或重置,因此在添加第二个项目之后,失败条件为真。

+0

我需要重置我的收藏。完全正确。 –

相关问题