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();
});
精彩评论