2010-12-15 30 views
0

我有一個正從命令行應用程序啓動的WPF應用程序。user32.dll FindWindowEx,通過遠程WPF窗口上的classname查找元素

我想要做一些簡單的自動操作(獲取/設置文本,點擊一些按鈕等)。我似乎無法找到WPF中的任何子窗口。我有WPF和UIA框架,WinForms和WinAPI的工作模型,但似乎無法讓WinAPI和WPF很好地發揮作用。我使用UISpy,WinSpy ++,Winspector,UIA驗證應用程序來查看控件等,但它們似乎沒有像WinForms一樣攜帶WPF的相同信息。

例如,在WinForms應用程序中,當通過間諜工具查看時,我看到一個ClassName爲「WindowsForms10.EDIT.app.0.33c0d9d」的文本框。 UIA自動化驗證應用程序是唯一確認元素存在並報告「文本框」的應用程序。

所以,我的問題是我如何找到正確的類名傳遞或有更容易的路線來找到子元素?

// does not work in wpf 
IntPtr child = NativeMethods.FindWindowEx(parent, prevElement, "TextBox", null); 

// works in winforms 
IntPtr child = NativeMethods.FindWindowEx(parent, prevElement, "WindowsForms10.EDIT.app.0.33c0d9d", null); 

這裏是進口user32.dll的我使用:

public class NativeMethods 
{ 
    public const int WM_SETTEXT = 0x000C; 
    public const int WM_GETTEXT = 0x000D; 
    public const uint CB_SHOWDROPDOWN = 0x014F; 
    public const uint CB_SETCURSEL = 0x014E; 
    public const int BN_CLICKED = 245; 
    public const uint WM_SYSCOMMAND = 0x0112; 
    public const int SC_CLOSE = 0xF060; 

    [DllImport("user32.dll", SetLastError = true)] 
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); 

    [DllImport("user32.dll", SetLastError = true)] 
    public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle); 

    [DllImport("user32.dll", SetLastError = false)] 
    public static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem); 

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)] 
    public static extern IntPtr SendMessage(HandleRef hWnd, uint Msg, IntPtr wParam, string lParam); 

    [DllImport("user32.dll")] 
    public static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam); 

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)] 
    public static extern int SendMessage(int hWnd, int Msg, int wParam, StringBuilder lParam); 


} 

回答

3

如果要自動WPF,你必須使用 UI自動化,而不是「過去的舊事「windows API :-)。

上有UI自動化這裏一個很好的介紹:Bugslayer: GUI Control to Major Tom

還有一個名爲「白」一個有趣的開源項目,它利用UI自動化:White on codeplex。如果你想挖掘,那裏有一些樣品。

+0

我更喜歡UI自動化路線。我有WPF和UI自動化,以及WinForms和WinAPI。這個練習的一部分是確定是否可以完成這個(WPF和WinAPI)。從下面的評論看,它看起來像WinForms和以前的應用程序,WinAPI是一個選項,WPF和超越使用UI自動化。謝謝! – ajberry 2010-12-15 19:17:46

+0

那麼,UI Automation也適用於常規的Windows和Winforms,因爲它可以依靠傳統的MSAA(輔助功能)SDK,但是,我的經驗表明,支持在所有平臺上都不完全一致。但是,如果您擁有服務器端代碼,您可以將自己的控件和UIElements與自動化對等設備配合使用,以方便外部客戶端處理,但UI自動化是WPF plus的真正走向。 – 2010-12-15 20:23:15