C#将焦点属性应用于FlowLayoutPanel,如按钮行为

时间:2016-02-15 12:46:57

标签: c# winforms

我尝试将焦点行为应用于FlowLayoutPanel,类似于按钮蓝色边框。我尝试使用GotFocus和LostFocus,但显然不是那样的。

private void FlowLayoutPanel_Click(object sender, EventArgs e)
{
    (sender as Control).BackColor = SystemColors.GradientActiveCaption;
    //More operations.
}

private void Panel_LostFocus(object sender, System.EventArgs e)
{
    (sender as Control).BackColor = default(Color);
    //More operations.
}

点击FlowLayoutPanel时没有任何反应,使用tab时,会一个接一个地调用这两个事件。

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

默认情况下,

FlowLayoutPanel不是可选控件。您可以通过派生void readfile(string a) { int i = 0; ifstream infile; infile.open(a.c_str()); string temp; //count how many elements are inside if(infile.is_open()) { while(infile.good()) { infile.getline(temp, 256, ","); i++; } infile.close(); i+=1; } else { cout<<"Error opening file."; } cout<<i; } 并设置FlowLayoutPanelSelectable control styles来创建自定义流布局面板,以便通过鼠标选择它。另外要接受制表位,请将UserMouse属性设置为true:

TabStop

然后,您可以处理GotFocusLostFocusEnterLeave事件。

答案 1 :(得分:2)

使用FLP的唯一目的是让它来安排子控件。始终是儿童控制获得焦点,而不是FLP。当然,没有任何反应。您必须订阅所有子控件的Enter事件才能看到焦点进入面板或其中一个子节点。离开是更难以正确,这将像一个便宜的汽车旅馆闪烁。

非常难看的解决方案,你不想这样做。使用Application.Idle事件,获得可靠事件的最佳选择是不切实际的。检查this.ActiveControl的Parent,如下所示:

    public Form1() {
        InitializeComponent();
        Application.Idle += CheckFlpFocus;
        this.Disposed += delegate { Application.Idle -= CheckFlpFocus; };
    }

    private bool FlpHasFocus;

    private void CheckFlpFocus(object sender, EventArgs e) {
        bool hasFocus = false;
        for (var ctl = this.ActiveControl; ctl != null; ctl = ctl.Parent) {
            if (ctl == flowLayoutPanel1) hasFocus = true;
        }
       if (hasFocus != FlpHasFocus) {
            FlpHasFocus = hasFocus;
            flowLayoutPanel1.BackColor = hasFocus ? Color.Black : Color.White;
        } 
    }