开发者

FileSystemWatcher.SynchronizingObject without a form

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 FileSys开发者_开发技巧temWatcher.SynchronizingObject property but don't know what to use since there is no main form in my application.


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.


You don’t need to pass any forms to Application.Run at all. Then you can save having to mess around with form visibility. Just do this:

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

Just one gotcha there - the form handle creation needs to be forced by accessing it once.


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 properties to false.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜