Before ole can be called, the current thread must be set to single thread unit (STA) mode

Time:2019-12-1

Today, after setting the relevant properties of combox’s fuzzy query function in WinForm,

this.comboBoxPM.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.comboBoxPM.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;

At runtime, the following error was reported

By looking for relevant information, we learned about sta cell mode and COM objects. In general, many controls in WinForm are COM objects, which can only be called by threads in sta mode.

There are two solutions:

First, add the [stathread] attribute label to the main method

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new LogInForm());
        }

The second is to set the unit state of a thread as a single thread unit, thread. Set apartment state (apartment state. STA);

Thread th = new Thread(()=> new Form1().ShowDialog());
th.SetApartmentState(ApartmentState.STA);
th.Start();

Finally, I use the second method to solve this problem, because my main form is opened in the way of thread in the login form (if I don’t open a new form in the way of thread, I can’t close the current form. ), at the beginning, there was no single thread unit mode set, so an error was reported. I have never encountered such a problem before. It took some time to finally solve the problem. Record it to avoid forgetting.