Home > other >  How to make correct initialization of ComboBox?
How to make correct initialization of ComboBox?

Time:05-03

I need show droppeddown combobox after start program. I need in dropdown style only, not simple style.

This is simple fragment of my program:

private void Form1_Shown(object sender, EventArgs e)
{
            CB1.Items.Add("1");
            CB1.DropDownStyle = ComboBoxStyle.DropDown;
            CB1.DroppedDown = true;
}
 

But I found the watch sign as cursor till I click on Form in any place. I guessed that my Form have not fully active state and wait for something.

When I click Form (or combobox or any control) by LBM, it activated fully and all works fine.

Of course the combobox is dropup then, so I need click combobox twice. And I wrote simple patch for it:

       private void Form1_Shown(object sender, EventArgs e)
        {
            CB1.Items.Add("1");
            CB1.DropDownStyle = ComboBoxStyle.DropDown;
            CB1.DroppedDown = true;
            Point pt = new Point();
            pt = CB1.PointToScreen(Point.Empty);
            pt.X = pt.X   CB1.Width - 5;
            pt.Y = pt.Y   5;
            Cursor.Position = pt;
             mouse_event((uint)(MouseEventFlags.LEFTDOWN | MouseEventFlags.LEFTUP), (uint)pt.X, (uint)pt.Y, 0, UIntPtr.Zero);
             mouse_event((uint)(MouseEventFlags.LEFTDOWN | MouseEventFlags.LEFTUP), (uint)pt.X, (uint)pt.Y, 0, UIntPtr.Zero);
        }

All works fine now. But tell me please what is correct initialization of such style combobox without any patch and without "Cursor = Cursors.Default;"

CodePudding user response:

You can simply wait until cursor is the default:

while (Cursor.Current != Cursors.Default)
{
    Application.DoEvents();
}

CB1.Items.Add("1");
CB1.DropDownStyle = ComboBoxStyle.DropDown;
CB1.DroppedDown = true;

Application.DoEvents simply process messages from the window queue, so you can process message until you get that cursor is the default. In that moment, you can drop down your control without problem.

If you prefer, create a extension method for the Form:

public static class FormExtends
{
    public static void WaitToDefaultCursor(this Form form)
    {
        while (Cursor.Current != Cursors.Default)
        {
            Application.DoEvents();
        }
    }
}

And use it:

this.WaitToDefaultCursor();

CB1.Items.Add("1");
CB1.DropDownStyle = ComboBoxStyle.DropDown;
CB1.DroppedDown = true;

NOTE: I use Cursor.Default but not to change the cursor. The form is processing messages and it's difficult to select a good moment to drop down the control.

  • Related