views:

216

answers:

1

Hi, I have a thread that listens for commands to my WPF application. If the WPF Application gets a command to take a screenshot the task is handed over to a "screenshotService". I found som code to take the screenshot somewhere on the interweb, seems to work, but i havent thought it through....i cannot take this screenshot from another thread, giving this exception:

{"This API was accessed with arguments from the wrong context."}

Left to say is that the signature of my screenshot method takes a UIElement from the UI, this grid is always the same one, and is pased to the constructor of the takeScreenshot method.

How would I go around and take this screenshot?

+1  A: 

Use a Dispatcher or a BackgroundWorker to do the job:

ThreadStart start = delegate()
{
   Dispatcher.Invoke(DispatcherPriority.Normal, 
                new Action<string>(TakeScreenshot), 
                "From Other Thread");
};

new Thread(start).Start();







BackgroundWorker _backgroundWorker = new BackgroundWorker();

_backgroundWorker.DoWork += _backgroundWorker_TakeScreenshot;


_backgroundWorker.RunWorkerAsync(5000);

void _backgroundWorker_TakeScreenshot(object sender, DoWorkEventArgs e)
{
}
luvieere
Doesn't this just pass the work back to the main UI thread?
Matt
Yes, it does, and that's what it is supposed to do, UI can only be updated from the UI thread.
luvieere
Thank you. So where do I call this, i receive the command with thread, and i guess that the above code should be executed from main thread? So do I have to move the dispatcher code to my UI? then how do I take the screenshot from my command thread?
H4mm3rHead
NVM. I figured that i might need an UI command queue and implemented it on my ordinary command queue. So now the UI checks in intervals if any UI commands are available from the command queue
H4mm3rHead
From the command thread, you invoke the dispatcher with the TakeScreenshot method in the UI thread. There, you take the screenshot. The line Dispatcher.Invoke(DispatcherPriority.Normal, new Action<string>(TakeScreenshot), "From Other Thread");goes where you want to take the screenshot in the command thread. It will call the method in the UI thread that executes the code from the screenshot service.
luvieere