FileSystemWatcher.SynchronizingObject without form

I have a Windows Form application written in C # in which I use FileSystemWatcher to track a folder for new files and then do some processing on them. My application is designed to run in the system tray and therefore does not launch any forms at startup. The problem is that the generated event is fired in a separate thread, and when I try to create an instance of the form in the created event, I get a ThreadStateException, which states that I need to work in SingleThreadApartment. I think I need to set the FileSystemWatcher.SynchronizingObject property, but I don’t know what to use, since there is no main form in my application.

+5
source share
3 answers

You will need to call Application.Run () in your Main () method to get the Windows Forms in sync in place so that FileSystemWatcher can properly march the call to the main thread. The problem that you will have is that the main form will become visible. Fix this by inserting this code into the class:

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

There is no limit to what your form looks like if you do.

+4
source

You do not need to submit any forms Application.Runat all. Then you can get rid of the need to tinker with the appearance of form. Just do the following:

var InvokerForm = new Form();
var dummy = InvokerForm.Handle; // force handle creation
Application.Run();

There is only one of them: the creation of a form descriptor must be obtained by contacting it once.

+2
source

- Application.Run.

SynchronizingObject .

To make sure that this is a hidden form, set properties ControlBox, and ShowInTaskbaris false.

+1
source

All Articles