views:

271

answers:

2

I have an windows form application written in C# in which I use a FileSystemWatcher to monitor a folder for new files and then perform some processing on them. My application is designed to run in the system tray and therefore does not instantiate any forms at startup. The problem is that the Created event is firing on a separate thread and when I try to create an instance of a form in the Created event I get an ThreadStateException that states I need to be running in SingleThreadApartment. I think I need to set the FileSystemWatcher.SynchronizingObject property but don't know what to use since there is no main form in my application.

+1  A: 

The simplest way to do this is to make a hidden form and pass it to Application.Run.

You can then set the SynchronizingObject property to the hidden form.

To make sure it's a hidden form, set the ControlBox and ShowInTaskbar proeprties to false.

SLaks
Actually, since `ISynchronizeInvoke` is implemented by `Control` I would imagine that it would be sufficient to create a `Control` instance and assign it to `SynchronizingObject`. Didn't try it, but it could work.
Fredrik Mörk
+1  A: 

You will have to call Application.Run() in your Main() method to get the Windows Forms synchronziation machinery in place so that FileSystemWatcher can properly marshal the call to the main thread. The problem you'll have then is that the main form will become visible. Fix that by pasting this code into the class:

    protected override void SetVisibleCore(bool value) {
        if (!this.IsHandleCreated) {
            this.CreateHandle();
            value = false;
        }
        base.SetVisibleCore(value);
    }

There are no restrictions on what your form looks like if you do this.

Hans Passant
Worked like a charm. Hidden form doesn't even flash on the screen.
AdmSteck