如何使用keybord焦点

时间:2015-07-13 09:24:09

标签: c# windows

我想创建一个下拉控件,该控件应该处于非活动状态并具有键盘输入焦点。所以我创建了一个控件如下。

public class DropDownEdit : UserControl
{
    [DllImport("user32.dll")]
    public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

    private const int WS_EX_TOOLWINDOW = 0x00000080;
    private const int WS_EX_TOPMOST = 0x00000008;
    private const int WS_EX_NOACTIVATE = 0x08000000;
    private const int WS_CHILD = 0x40000000;
    private const int WS_POPUP = unchecked((int)0x80000000);

    private TextBox text = new TextBox();

    public DropDownEdit()
    {
        this.BackColor = Color.FromArgb(44, 68, 107);
        this.Controls.Add(text);
        this.Margin = Padding.Empty;
        this.Padding = new Padding(0);
        text.Multiline = true;
        text.ScrollBars = ScrollBars.Both;
        text.Size = new Size(this.Width, this.Height);
    }

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams createParams = base.CreateParams;
            createParams.Style &= ~WS_CHILD;
            createParams.Style |= WS_POPUP;

            createParams.ExStyle |= WS_EX_TOOLWINDOW;
            createParams.ExStyle |= WS_EX_TOPMOST;
            createParams.ExStyle |= WS_EX_NOACTIVATE;
            return createParams;
        }
    }

    public void ShowWindow(Point point)
    {
        text.Focus();
        this.Capture = true;
        SetParent(this.Handle, IntPtr.Zero); 
        this.Location = point;
        Show();
    }

    protected override void OnMouseCaptureChanged(EventArgs e)
    {
        base.OnMouseCaptureChanged(e);
        this.Hide();
    }
}

当我显示上面的下拉窗口时,

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Point point = this.PointToScreen(button1.Location);
        DropDownEdit window = new DropDownEdit();
        window.ShowWindow(new Point(point.X, point.Y + 20));
    }
}

Form1在显示DropDownEdit时闪烁。我认为DropDownEdit被激活,Form1失去激活。如何在Form1中避免这种闪烁?

注意: - 我需要在下拉控件中关注TextBox

0 个答案:

没有答案