繁体   English   中英

以编程方式单击按钮 C#

[英]Click a button programmatically C#

我正在寻找一种以编程方式单击按钮的方法(Winform)。 我的项目有一个表单(比如 Form2)和按钮(Button2)。 当我单击我的按钮时,它应该单击 Button1(在另一个项目中),但两者都在同一个解决方案中。 这就是我试图做的:

private void button2(object sender, EventArgs e)
{

    System.IntPtr hwnd;

    System.IntPtr hwndChild = IntPtr.Zero;

    hwnd = FindWindow(null, "form1");

    if (hwnd.Equals(IntPtr.Zero))
    {
     MessageBox.Show("Couldn't find the form");
    }
    else
    {
    hwndChild = FindWindowEx((IntPtr)hwnd, IntPtr.Zero, null, "BUTTON1");

    if(!hwndChild.Equals(IntPtr.Zero))
    SendMessage(hwndChild, BM_CLICK, IntPtr.Zero, IntPtr.Zero);
    }
}

我应该使用任何其他方法(例如反射)而不是这种方法吗?

PS:Button1 是私有的,不能对该功能/项目进行任何更改

操作:

我正在寻找一种以编程方式单击按钮的方法(Winform)。

Button1 和 Button2 处于两个不同的进程中。 我不应该对包含 button1 的代码进行任何更改。

当然,不需要对目标应用程序进行任何更改的最简单的方法是使用Windows UI 自动化 UIA 本质上允许您从 GUI 角度自动化另一个应用程序(而不是说通过 COM/Ole 自动化在幕后),无论您是只想驱动另一个应用程序,比如单击一个按钮,还是在 QA 中执行全面的自动化测试.

微软:

Microsoft UI 自动化是一个辅助功能框架,它使 Windows 应用程序能够提供和使用有关用户界面 (UI) 的编程信息。 更多的...

...和:

UIA 可用于自动化本机 Windows 应用程序、WPF 应用程序以及 Silverlight 应用程序。 更多的...

此代码将在标题为“Target Demo”的窗口中单击包含文本“Click Me”的按钮。 注意我没有引用任何特定的对象类型; 回调或 GUI 技术(这适用于本机;WinForms;WPF 和 Web)

//
// This is the handler in the ButtonClicker app, the app that is doing the clicking
//
private void go_Click(object sender, EventArgs e)
{
    // Look for a top-level window/application called "Target Demo"
    var root = AutomationElement.RootElement;
    var condition1 = new PropertyCondition(AutomationElement.NameProperty, "Target Demo");

    var treeWalker = new TreeWalker(condition1);
    AutomationElement element = treeWalker.GetFirstChild(root);
    
    if (element == null)
    {
        // not found
        return;
    }

    // great!  window found
    var window = element;

    // now look for a button with the text "Click Me"
    var buttonElement =window.FindFirst(TreeScope.Children, 
        new PropertyCondition(AutomationElement.NameProperty, "Click Me"));
    if (buttonElement == null)
    {
        // not found
        return;
    }

    // great! now click the button
    var invokePattern = buttonElement.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;
    invokePattern?.Invoke();

}

好处

  • 定位应用程序所需的零更改
  • 无需担心查找窗口句柄
  • 不要试图向应用程序的消息泵发送 BN_CLICK 通知,希望它能正常工作
  • 适用于 C++ 应用程序; WinForms; WPF; 网络

你有几个选项,如下所示

1- button1.PerformClick();

2- button1_Click(this, EventArgs.Empty);

3- button1(null, null)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM