-1

I have, Windows Form, which have System.Timers.Timer in elapsed event of this timer, I wish to popup a form using ShowDialog(), over there while creating object of that form itself, I am getting following error.

Current thread must be set to single thread apartment (STA) mode before OLE calls can be made

As suggested in some other SO post, I had decorated Main() which initializes this form with [STAThread] attribute.

But still getting same error, now when I debug, exception is generated at,

this.TheDropDownObject.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;

where I set AutoCompleteMode of Dropdown control in that form,

As suggested in yet another SO post, I had done this through code instead of in designer but tough luck.

Now Suppose, I create object on some other event then it is working, else if skip setting this AutoCompleteMode then still it is triggered from timer.

Can anyone please tell me what is going wrong, and how can I get this achieved?

Aniket Bhansali
  • 630
  • 12
  • 33

1 Answers1

0

Try to use this:

Thread t = new Thread(Worker); 
// Make sure to set the apartment state BEFORE starting the thread. 
t.ApartmentState = ApartmentState.STA; 
t.Start(); 
t.Join();

public void Worker()
{
     //your code
}

and use this GUI element in this Thread.

MatKai
  • 182
  • 1
  • 3
  • 9
  • Thanks, but it isn't any function I need to call, I am getting error when Creating Form object in timer_elapsed event. – Aniket Bhansali Jan 08 '18 at 13:06
  • It's becouse you cant create and use GUI object just like that. You have to declare that you use it in STA and use it only in one thread at a time. – MatKai Jan 08 '18 at 13:37
  • You can read this https://stackoverflow.com/questions/127188/could-you-explain-sta-and-mta, maybe it will help you understand. Or maybe I dont understand your issue, you could give me some code here to clarify all. – MatKai Jan 08 '18 at 13:40