我有一个场景.(Windows Forms,C#,.NET)
UserControl_Load
方法,则UI在加载方法执行的持续时间内变得无响应.伪代码看起来像这样:
代码1
UserContrl1_LoadDataMethod()
{
if (textbox1.text == "MyName") // This gives exception
{
//Load data corresponding to "MyName".
//Populate a globale variable List<string> which will be binded to grid at some later stage.
}
}
Run Code Online (Sandbox Code Playgroud)
它给出的例外是
跨线程操作无效:从创建它的线程以外的线程访问控件.
为了更多地了解这一点,我做了一些谷歌搜索,并提出了一个建议,如使用下面的代码
代码2
UserContrl1_LoadDataMethod()
{
if (InvokeRequired) // Line #1
{
this.Invoke(new MethodInvoker(UserContrl1_LoadDataMethod));
return;
}
if (textbox1.text == "MyName") // Now it wont give an exception
{
//Load data correspondin to "MyName"
//Populate a globale …
Run Code Online (Sandbox Code Playgroud) 我正在尝试注册一个热键,我正在翻译这个 C++代码,我写道:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
[DllImport("user32.dll")]
public static extern
bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, int vk);
[DllImport("user32")]
public static extern
bool GetMessage(ref Message lpMsg, IntPtr handle, uint mMsgFilterInMain, uint mMsgFilterMax);
public const int MOD_ALT = 0x0001;
public const int MOD_CONTROL = 0x0002;
public const int MOD_SHIFT = 0x004;
public const int MOD_NOREPEAT = 0x400;
public const int WM_HOTKEY = 0x312;
public const int DSIX = 0x36; …
Run Code Online (Sandbox Code Playgroud) 如何创建使用键盘快捷键执行操作的应用程序(应用程序必须是不可见的).例如,当用户按Ctrl+ Alt+ 时显示MessageBox W.
在Windows应用程序中,当使用多个线程时,我知道有必要调用主线程来更新GUI组件.如何在控制台应用程序中完成?
例如,我有两个线程,一个主线程和一个辅助线程.辅助线程始终在侦听全局热键; 当它被按下时,辅助线程执行一个事件,该事件延伸到win32 api方法AnimateWindow.我收到一个错误,因为只允许主线程执行所述函数.
当"调用"不可用时,如何有效地告诉主线程执行该方法?
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 …
Run Code Online (Sandbox Code Playgroud)