问题描述
我在主函数中实例化了一个名为 watcher的FileSystemWatcher对象。在 watcher.renamed事件期间,我尝试将文本存储在剪贴板中的字符串变量中,但是它总是返回空数据吗?我在断点的帮助下检查了变量的值,该变量的值仍然为空。
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.
这是代码:
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.
推荐答案
剪贴板
访问方法必须从STA启动线程才能正常运行。不幸的是, FileSystemWatcher
在线程池线程上运行其回调,所有这些都是MTA的一部分。这样,尝试访问剪贴板在您的示例中将行不通。
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.
如果在运行事件处理程序时需要执行一些UI工作,则您您需要将其通知表单(或用户界面的其他部分)。您可以使用 Form
对象的 BeginInvoke()
方法发布要在UI线程上运行的方法:
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);
}));
}
这篇关于在FileSystemWatcher的重命名事件中无法访问剪贴板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!