Unable to access clipboard in FileSystemWatcher's renamed event

Deadly 提交于 2019-12-11 20:40:07

问题


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 :)



来源:https://stackoverflow.com/questions/16403609/unable-to-access-clipboard-in-filesystemwatchers-renamed-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!