使用DLL名称获取表单数据

时间:2014-01-02 11:04:35

标签: c# windows winforms

我正在一个应用程序上创建一个工具,打开一些窗体表格以获取用户的信息,我的工具应该自己处理这些窗体,而无需用户的交互。 我已经启动了一个事件,以便在打开表单的过程时通过以下代码获取它:

mgmtWtch = new ManagementEventWatcher("Select * From Win32_ProcessStartTrace");
mgmtWtch.EventArrived += WatchManagementEvent;
mgmtWtch.Start();

显示的窗口有OK按钮,我想点击,我不知道如何进行此操作。虽然我可以从这个事件获得的参数是

  

EventArrivedEventArgs e

我的问题是如何通过此事件处理程序单击“确定”按钮?

提前感谢。

1 个答案:

答案 0 :(得分:1)

你看过.Net的GUI自动化API吗?

您需要 UIAutomationClient UIAutomationTypes 程序集。

我已经使用此API在测试期间驱动安装程序,UI。

我发现此链接最初很有用。

http://blogs.msdn.com/b/oldnewthing/archive/2013/04/08/10409196.aspx

e.g。假设你有按钮的父窗口(即表格),你知道按钮的ID:

using System.Windows.Automation;
....
static AutomationElement FindById(AutomationElement root, string id, bool directChild)
{
    Assert(root != null, "Invalid input: ParentWindow element 'root' is null.");

    Condition conditions = new PropertyCondition(AutomationElement.AutomationIdProperty, id);

    return root.FindFirst(directChild ? TreeScope.Children : TreeScope.Descendants, conditions);
}
....
AutomationElement button = FindById(containerWindow, id.ToString(), true);

InvokePattern invokePattern = null;
try
{
    invokePattern = button.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;
}
catch (InvalidOperationException)
{
    MessageBox.Show("The UI element named " + button.GetCurrentPropertyValue(AutomationElement.NameProperty) + " is not a button");

    return false;
}

invokePattern.Invoke();

如果您不知道按钮的ID,但确实知道它的名称,即按钮上的文字,请将AutomationElement.AutomationIdProperty替换为AutomationElement.NameProperty中的FindById(并适当地重命名方法)< / p>

假设按钮位于顶级窗体窗口中,并且您知道此窗体窗口中显示的标题,则以下代码将显示按钮的父窗口:

bool ignoreCase = true; // or false if preferred
Condition conditions = new PropertyCondition(
    AutomationElement.NameProperty,
    windowTitle,
    ignoreCase ? PropertyConditionFlags.IgnoreCase : PropertyConditionFlags.None
);

AutomationElement myForm =
    AutomationElement.RootElement.FindFirst(
        TreeScope.Children,
        conditions );

可以通过流程'MainWindowTitle属性从您已拥有的流程中检索窗口标题。