In a Windows Application, when multiple threads are used, I know that it’s necessary to invoke the main thread to update GUI components. How is this done in a Console Application?
For example, I have two threads, a main and a secondary thread. The secondary thread is always listening for a global hotkey; when it is pressed the secondary thread executes an event that reaches out to the win32 api method AnimateWindow. I am receiving an error because only the main thread is allowed to execute said function.
How can I effectively tell the main thread to execute that method, when "Invoke" is not available?
update: if it helps, here is the code. To see the HotKeyManager stuff(where the other thread is coming into play), check out the answer to this question
class Hud
{
bool isHidden = false;
int keyId;
private static IntPtr windowHandle;
public void Init(string[] args)
{
windowHandle = Process.GetCurrentProcess().MainWindowHandle;
SetupHotkey();
InitPowershell(args);
Cleanup();
}
private void Cleanup()
{
HotKeyManager.UnregisterHotKey(keyId);
}
private void SetupHotkey()
{
keyId = HotKeyManager.RegisterHotKey(Keys.Oemtilde, KeyModifiers.Control);
HotKeyManager.HotKeyPressed += new EventHandler<HotKeyEventArgs>(HotKeyManager_HotKeyPressed);
}
void HotKeyManager_HotKeyPressed(object sender, HotKeyEventArgs e)
{
ToggleWindow();
}
private void ToggleWindow()
{
//exception is thrown because a thread other than the one the console was created in is trying to call AnimateWindow
if (isHidden)
{
if (!User32.AnimateWindow(windowHandle, 200, AnimateWindowFlags.AW_VER_NEGATIVE | AnimateWindowFlags.AW_SLIDE))
throw new Win32Exception(Marshal.GetLastWin32Error());
}
else
{
if (!User32.AnimateWindow(windowHandle, 200, AnimateWindowFlags.AW_VER_POSITIVE | AnimateWindowFlags.AW_HIDE))
throw new Win32Exception(Marshal.GetLastWin32Error());
}
isHidden = !isHidden;
}
private void InitPowershell(string[] args)
{
var config = RunspaceConfiguration.Create();
ConsoleShell.Start(config, "", "", args);
}
}