开发者

Getting data off the Clipboard inside a BackgroundWorker

开发者 https://www.devze.com 2023-04-10 22:10 出处:网络
I have a background worker and in the DoW开发者_StackOverflowork method I have the following: var clipboardData = Application.Current.Dispatcher.Invoke(new Action(() => { Clipboard.GetData(DataFo

I have a background worker and in the DoW开发者_StackOverflowork method I have the following:

 var clipboardData = Application.Current.Dispatcher.Invoke(new Action(() => { Clipboard.GetData(DataFormats.Serializable); }));

Why does this always return null even though I know there is data on the clipboard in the correct format?


Try putting the call into an STA thread:

object data = null;
Thread t = new Thread(() =>
{
    data = Clipboard.GetData(DataFormats.Serializable);
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
// 'data' should be set here.

Within a method with an "OnFinished" action:

void GetClipboardData(Action<Object> OnFinished)
{
    Thread t = new Thread(() =>
    {
        object data = Clipboard.GetData(DataFormats.Serializable);
        OnFinished(data);
    });
    t.SetApartmentState(ApartmentState.STA);
    t.Start();
}

You'd use it like this:

GetClipboardData((data) =>
{
    // 'data' is set to the clipboard data here.
});

If you want to show and hide a window, try this:

myWindow.Show();
GetClipboardData((data) =>
{
    // Do something with 'data'.
    myWindow.Close();
});

With ShowDialog():

Thread d = new Thread(() =>
{
    myWindow.ShowDialog();
});
d.SetApartmentState(ApartmentState.STA);
d.Start();
GetClipboardData((data) =>
{
    // 'data' is set to the clipboard data here.
   myWindow.Close();
});
0

精彩评论

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

关注公众号