Unable to access clipboard in FileSystemWatcher

2019-09-04 20:12发布

问题:

I have an object of FileSystemWatcher called 'watcher' instantiated in my main function. I tried to store the text on clipboard in a string variable during the 'watcher.renamed' event but it always returns empty data? I checked the value of the variable with the help of a breakpoint, it remains empty.

Here is the code:

private void Form1_Load(object sender, EventArgs e)
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = Application.StartupPath;
        watcher.Filter = Path.GetFileName(Application.StartupPath+ @"\RBsTurn.txt");
        watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
        watcher.EnableRaisingEvents = true;
    }

    void watcher_Renamed(object sender, RenamedEventArgs e)
    {
        string x = Clipboard.GetText();
        MessageBox.Show(x);
    }

This code, always displays an empty text box when the file is renamed.. Please help.

回答1:

Clipboard access methods must be initiated from an STA thread in order to function properly. Unfortunately, the FileSystemWatcher runs its callbacks on threadpool threads, all of which are part of the MTA. As such, trying to access the clipboard isn't going to work in your example.

If you need to perform some UI work when your event handler is run, then you'll need to notify the form (or some other piece of the UI) about that. You can use the Form object's BeginInvoke() method to post a method to run on the UI thread:

void watcher_Renamed(object sender, RenamedEventArgs e)
{
    this.BeginInvoke(new Action(() => {
        string x = Clipboard.GetText();
        MessageBox.Show(x);
    }));
}


回答2:

The trick was to create a new thread in the event handler and set its STA properties

Here is the code

 private void Form1_Load(object sender, EventArgs e)
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = Application.StartupPath;
        watcher.Filter = Path.GetFileName(Application.StartupPath+ @"\RBsTurn.txt");
        watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
        watcher.EnableRaisingEvents = true;
    }

    void watcher_Renamed(object sender, RenamedEventArgs e)
    {
        Thread th = new Thread(() =>
        {
            Clipboard.Clear();
        });

        th.IsBackground = true;
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
     }

Hope it helps :)