1 year ago

#382278

test-img

Spook

How to set AutomationId for dynamically created controls in Windows Forms?

I'm trying to set AutomationId for dynamically created items. The example code is as following:

public Form1()
{
    InitializeComponent();
    var menu = new MenuStrip();
    
    var item = new ToolStripMenuItem();
    item.Text = "Plik";
    item.Name = "File";            
    

    var subitem = new ToolStripMenuItem();
    subitem.Text = "Nowy";
    subitem.Name = "New";

    item.DropDownItems.Add(subitem);

    this.Controls.Add(menu);
    menu.Items.Add(item);

    this.MainMenuStrip = menu;
}

private void button1_Click(object sender, EventArgs e)
{
    var formHandle = AutomationElement.FromHandle(this.Handle);

    Condition propCondition = new PropertyCondition(
        AutomationElement.NameProperty, "File");

    var menuHandle = formHandle.FindFirst(TreeScope.Descendants, propCondition);
    // menuHandle is null here
    menuHandle.SetFocus();
}

Form itself has AutomationId equal to "Form1". However, created menu items doesn't seem to have AutomationID.

How can I manually set AutomationId for dynamically created control?

winforms

ui-automation

0 Answers

Your Answer

Accepted video resources