tags:

views:

69

answers:

1

I have an intermittent problem where I cannot create an instance of the System.Windows.Forms.Form class in my C# library. I log exceptions in my program, but unfortunately nothing was recorded for this problem. It might not be relevant, but my library, called via COM (i.e. there is no Main method).

So I threw a test exception, and it was caught and logged successfully -- so I'm thinking that maybe something screwy is going on in the message loop?

Update 1

The Form is created using the following code in a Thread which has ApartmentState.STA set.

  someForm = new Form();
  someForm.Visible = false;
  someForm.Text = "Hello world!";
+1  A: 

It's just a guess, since you've provided no code and little context, but might you be missing the STAThread attribute on your entry point method (Main)? This is necessary for WinForms apps that make use of COM.

Noldorin
Ah, actually the entry point is not via Main, it is via a COM call. Have you ever seen `someForm = new Form();` throw an exception?
nbolton
I hope this is the right answer! I love it when people take a shot in the dark and hit!
Iain Galloway
@Iain: Heh, I hope so too. It's a game, really - might just get lucky! It's the first possible solution that came to mind from experience though.
Noldorin
Noldorin: I have looked in to the code a little more and it seems that the thread in which I am creating the `Form` does indeed have `ApartmentState.STA` passed to it's `SetApartmentState` method. So I think that in this case lack of STA is not the issue. Any other ideas why I am unable to create an instance of `Form`? Memory issues perhaps?
nbolton
@nbolton: Ok, glad you checked that at least. No other thoughts at the moment, sorry, will let you know if I do.
Noldorin
Noldorin: Thanks -- hmm, maybe someone could suggest a way of causing `new Form()` to throw an exception? Though, it may still be one of the other two lines which set the `Visible` and `Text` properties.
nbolton