自定义控件 - 无法接收焦点或鼠标事件

时间:2013-07-25 15:15:47

标签: c# winforms events focus

我已经创建了一个Winforms自定义控件,虽然可以很好地接收MouseWheel消息,但是没有收到MouseDown,MouseMove或MouseUp消息。

我设置了以下ControlStyles:

SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer |
ControlStyles.AllPaintingInWmPaint, true);

(我也尝试过设置ControlStyles.SelectableControlStyles.UserMouse,但没有区别)

我已将代码放入GotFocusLostFocus事件中,我可以看到在某些情况下控件确实会获得焦点,只会立即再次失去它。

这是一个GIS地图查看器/编辑器控件,它必须能够接收焦点,以便它可以接收鼠标事件,还可以使用热键来执行各种操作。

有什么想法吗?

[编辑:  这里有一些代码可以证明这一点。我猜这个问题与Setting Focus to a .NET UserControl...?相同,但没有得到令人满意的回答。 ]

public partial class CustomControl1 : Control
{
    public CustomControl1()
    {
        SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.Selectable | ControlStyles.UserMouse, true);
        MouseWheel += CustomControl1_MouseWheel;
        MouseDown += CustomControl1_MouseDown;
        MouseMove += CustomControl1_MouseMove;
        MouseUp += CustomControl1_MouseUp;
    }

    void CustomControl1_MouseUp(object sender, MouseEventArgs e)
    {
        Debug.Write("MouseUp"); // never gets fired
    }

    void CustomControl1_MouseMove(object sender, MouseEventArgs e)
    {
        Debug.Write("MouseMove"); // never gets fired
    }

    void CustomControl1_MouseDown(object sender, MouseEventArgs e)
    {
        Debug.Write("MouseDown"); // never gets fired
    }

    void CustomControl1_MouseWheel(object sender, MouseEventArgs e)
    {
        Debug.Write("MouseWheel"); // works fine!
    }

    protected override void OnPaint(PaintEventArgs pe)
    {
        // do some drawing stuff here
    }
}

0 个答案:

没有答案