2012-11-05 87 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

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

相關問題