【发布时间】:2011-04-09 01:08:03
【问题描述】:
在 Windows 应用程序中,当使用多个线程时,我知道需要调用主线程来更新 GUI 组件。这是如何在控制台应用程序中完成的?
例如,我有两个线程,一个主线程和一个辅助线程。辅助线程始终在监听全局热键;当它被按下时,辅助线程会执行一个到达 win32 api 方法 AnimateWindow 的事件。我收到一个错误,因为只允许主线程执行所述功能。
当“Invoke”不可用时,如何有效地告诉主线程执行该方法?
更新: 如果有帮助,这里是代码。要查看 HotKeyManager 的内容(另一个线程正在发挥作用),请查看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);
}
}
【问题讨论】:
标签: c# multithreading winapi console-application