UI Automation switch window

谁都会走 提交于 2021-02-08 14:14:43

问题


I've noticed that setforegroundwindow can be very flaky - no matter how you do it.

I've noticed that using UIAutomation, where possible, seems to improve things.

For example:

Getting the WindowPattern and using something like:

windowPattern.SetWindowVisualState( WindowVisualState.Normal );

windowPattern.SetWindowVisualState( WindowVisualState.Maximized );

Now my questions is:

How do I know whether I should make it maximized or normal. The task manager, and dragon naturally speaking both seem to know how to do this. If it was previous maximized, and then minimized, I'd like to maximize the window when I switch to it. If it was previously not maximized, I'd like to make it "Normal".

Any ideas?


回答1:


SetFocus for AutomationElement didn't work.

From the following question: Get window state of another process

I found that the GetPlacement api gave me what I needed:

     if ( (windowplacement.flags & WPF_RESTORETOMAXIMIZED) > 0 )
     {
        windowPattern.SetWindowVisualState( WindowVisualState.Maximized );
     }
     else
     {
        windowPattern.SetWindowVisualState( WindowVisualState.Normal );
     }

With this the window will restore to maximized if it was maximized and restore to normal if it was not maximized.




回答2:


Ok, I misunderstood the question. I believe the key to doing what you want is to use the AutomationElement.SetFocus() method.

Here's a basic example.

//I assume you already have some way of getting the window's handle
var wih = new System.Windows.Interop.WindowInteropHelper(window);
IntPtr hWnd = wih.Handle;

//get the automation element from the handle
var ae = AutomationElement.FromHandle(hWnd);

//this will bring the window into focus.
ae.SetFocus();



回答3:


You may use the WindowPattern to set window to foreground as follows:

var p =
 (WindowPattern)_w.AutomationElement.GetCurrentPattern(WindowPattern.Pattern);
p.SetWindowVisualState(WindowVisualState.Normal);


来源:https://stackoverflow.com/questions/17656045/ui-automation-switch-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!