0

可能重复:
面板没有获得焦点

我在winform中测试面板控件,我遇到了一个问题。

我将这 2 个事件添加到面板中,但没有一个事件触发:

 private void panel_onFocus(object sender, EventArgs e)
    {
        panel1.Size = new Size(panel1.Size.Width, panel1.Size.Height * panel1.Size.Height);
    }

    private void panel_lostFocus(object sender, EventArgs e)
    {
        panel1.Size = new Size(panel1.Size.Width, panel1.Size.Height / panel1.Size.Height);
    }

我在表单上有另一个控件来测试焦点(一个按钮)。

为什么 onFocus 和 lostFocus 不火?

(对不起我的英语)

4

2 回答 2

1

以下是一个可选面板(继承自常规面板)

面板获得焦点没有得到关注

尝试这个。在您的项目中添加此类。只是改变namespace yourApplicaionName。编译你的项目。然后你会selectablePanel在你的工具箱中看到。您可以使用它代替普通面板。希望您能够专注于这个面板

using System;
using System.Drawing;
using System.Windows.Forms;

namespace yourApplicaionName
{
    class selectablePanel : Panel
    {
        public selectablePanel()
        {
            this.SetStyle(ControlStyles.Selectable, true);            
            ResizeRedraw = true;
            this.TabStop = true;
        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            this.Focus();
            base.OnMouseDown(e);
        }

        protected override bool IsInputKey(Keys keyData)
        {
            if (keyData == Keys.Up || keyData == Keys.Down) return true;
            if (keyData == Keys.Left || keyData == Keys.Right) return true;
            return base.IsInputKey(keyData);
        }

        protected override void OnEnter(EventArgs e)
        {
            this.Invalidate();
            base.OnEnter(e);
        }

        protected override void OnLeave(EventArgs e)
        {
            this.Invalidate();
            base.OnLeave(e);
        }

        protected override void OnPaint(PaintEventArgs pe)
        {
            base.OnPaint(pe);
            if (this.Focused)
            {
                var rc = this.ClientRectangle;
                rc.Inflate(-2, -2);
                ControlPaint.DrawFocusRectangle(pe.Graphics, rc);
            }
        }
    }
}
于 2012-10-26T17:18:36.023 回答
0

首先 lostFocus 将高度设置为 1,onGotFocus 将乘以 1*1,即 1 实际上不会改变任何内容。

于 2012-10-26T16:40:33.003 回答