简体   繁体   English

C#添加按钮以进行流控制而不会失去焦点

[英]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. 我将其放在计时器上,每隔X秒刷新一次,然后清除并添加按钮。 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. 多亏了LarsTech,我研究了如何正确处理添加到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. 通过更改OnClick事件将焦点更改为标签,可以解决主要问题,而这又不会导致每次清除并重新添加控件时,主表单都获得最高的排名。 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();
        }
    }

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

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