简体   繁体   中英

C# add buttons to flow control without stealing focus

In my application I dynamically create buttons and add them to a flow control that is later cleared. I have this on a timer to refresh every X seconds to clear then add buttons. This is all being done on the main form.

The problem is when I have a child form launched the main form will steal focus every time the controls are added to the flow control.

Here is the code I have that dynamically clears and adds the controls on the main form.

I call this before adding the controls

flw_users.Controls.Clear();

This is what I call to dynamically create/add the buttons to the flow control.

private void DisplayNewMobileUser(string MobileUserName)
    {

        // Set Button properties
        Button button = new Button();
        button.Text = MobileUserName;
        button.Size = new System.Drawing.Size(171, 28);
        button.Name = MobileUserName;


        button.BackColor = System.Drawing.Color.White;
        button.FlatAppearance.BorderColor = System.Drawing.Color.White;
        button.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);

        button.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
        button.ForeColor = System.Drawing.Color.Black;
        button.Margin = new System.Windows.Forms.Padding(0, 1, 0, 1);
        button.TextAlign = System.Drawing.ContentAlignment.TopLeft;



        button.Click += new EventHandler(MobileUserName_OnClick);
        flw_users.Controls.Add(button);
    }

Is there a way to add buttons to a flow control with out it always stealing focus ?

Thanks to LarsTech I researched how to properly dispose each control added to flw_users. The main issues was fixed by changing the OnClick event to change focus to a label, which in turn didn't cause the main form to gain topmost every time the controls were cleared and re added. So everytime I clicked a button that button still had focus while the new form appeared.

Thanks everyone !

Here is the code I used to properly clear the controls

private void ClearUsers()
    {
        List<Control> ctrls = new List<Control>();

        foreach (Control c in flw_users.Controls)
        {
            ctrls.Add(c);
        }

        flw_users.Controls.Clear();

        foreach (Control c in ctrls)
        {
            c.Dispose();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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