2013-07-15 81 views
6

我注意到,setforegroundwindow可以非常脆弱 - 无论你如何做。UI自动切换窗口

我注意到在可能的情况下使用UIAutomation似乎可以改善事情。

例如:

获取WindowPattern并使用类似:

windowPattern.SetWindowVisualState(WindowVisualState.Normal); 

windowPattern.SetWindowVisualState(WindowVisualState.Maximized); 

现在我的问题是:

我如何知道我是否应该让它最大化还是正常的。任务管理员和龙自然地说,似乎都知道如何做到这一点。如果它以前最大化,然后最小化,我想在切换到最大化窗口时使用。如果它以前没有最大化,我想使它成为“正常”。

任何想法?

回答

2

SetFocus for AutomationElement没有工作。

从以下问题: Get window state of another process

我发现GetPlacement API给我我需要的东西:

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

有了这个窗口将恢复到最大化,如果它是最大化,并恢复到正常如果它没有最大化。

1

好吧,我误解了这个问题。我相信做你想做的事情的关键是使用AutomationElement.SetFocus()方法。

下面是一个基本的例子。

//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(); 
+1

这是有点用,但我需要知道在什么通过为的visualSTATE使用。假设我正在制作一个任务切换应用程序。我有hwnd,然后AutomationElement为当前在任务栏中最小化的窗口。我不知道如何查看窗口WAS是否处于最大化或正常状态。所以我不知道我是否应该通过“正常”或“最大化”这个功能。 – Derek

+0

@Derek我已经更新了我的答案,并且我认为它可以帮助您更好地寻找答案。我做了一些非常基本的测试,它看起来和“切换到”在任务管理器中工作的方式一样。 – Gray

1

您可以使用WindowPattern到窗口设置前景色为:

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