N unit-Can't access toolstrip button using button name in windows forms

SanthoshPichumanu 6 Reputation points
2020-12-21T11:22:56.057+00:00

I’m trying to access a toolstrip button in windows forms using button name in windows forms but facing null reference exception as end result. Normally I can access button using its name, but i am facing issue in accessing the button in toolstrip. This issue occur in N unit framework and access button using automation element. Can anyone guide me for this issue ?

Code snippet for accessing button:

enter code here
    public static AutomationElement WindowElement;
    public  void ClickButton()
    {
        object objPattern;
        AutomationElement click = WindowElement.FindFirst(TreeScope.Descendants,
         new PropertyCondition(AutomationElement.NameProperty, "toolStripButton2"));
        click.TryGetCurrentPattern(InvokePattern.Pattern, out objPattern);
        ((InvokePattern)objPattern).Invoke();
    }

Code snippet for toolstrip:

enter code here
// toolStrip1
        // 
        this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
        this.toolStripButton1,
        this.toolStripComboBox1,
        this.toolStripButton2});
        this.toolStrip1.Location = new System.Drawing.Point(0, 0);
        this.toolStrip1.Name = "toolStrip1";
        this.toolStrip1.Text = "toolStrip1";
        // 
        // toolStripButton1
        // 
        this.toolStripButton1.Name = "toolStripButton1";
        this.toolStripButton1.Text = "toolStripButton1";
        // 
        // toolStripComboBox1
        // 
        this.toolStripComboBox1.Name = "toolStripComboBox1";
        this.toolStripComboBox1.Size = new System.Drawing.Size(121, 25);
        // 
        // toolStripButton2
        // 
        this.toolStripButton2.Name = "toolStripButton2";
        this.toolStripButton2.Text = "toolStripButton2";
        //
    private System.Windows.Forms.ToolStrip toolStrip1;
    private System.Windows.Forms.ToolStripButton toolStripButton1;
    private System.Windows.Forms.ToolStripComboBox toolStripComboBox1;
    private System.Windows.Forms.ToolStripButton toolStripButton2;
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,135 questions
0 comments No comments
{count} vote

1 answer

Sort by: Most helpful
  1. Lex Li (Microsoft) 4,742 Reputation points Microsoft Employee
    2020-12-22T04:00:24.177+00:00

    https://learn.microsoft.com/en-us/dotnet/api/system.windows.automation?view=net-5.0 that namespace is strictly for WPF only.

    To unit test a WinForms app, you might try to use https://github.com/microsoft/WinAppDriver on Windows 10.