我正在开发一个运行在嵌入式设备上的WPF应用程序(用于嵌入式的.NET标准4)。它有很多硬件,当我测试时会遇到阻碍,所以我创建了一个DummyHardware接口,在我运行单元测试时,或者在我的开发PC上独立运行时,除了打印日志消息之外,它什么也不做。
到目前一切尚好。但是:该设备有一个4键键盘,这是民意测验。当等待按下一个键时,我的虚拟键盘类进入了一个无限循环,因为没有键可按:-)所以我想,“好的,我将轮询键盘,看看是否按下了1、2、3或4”。但我有例外
调用线程一定是STA..。
当我给Keyboard.IsKeyDown( Key.D1 )打电话的时候。键盘轮询是在一个单独的线程中进行的(以便与其他硬件中通常较慢的串行通信分离)。对如何进行有什么想法吗?召唤?
注意:一种选择是跳过虚拟硬件上的“等待密钥”测试,但是我不知道按下了哪个键,而下面的依赖于它的代码将不能正常工作。尤克。
发布于 2013-10-18 11:12:28
您可以将ApartmentState设置为STA。使用Thread.SetApartmentState方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace staThread
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Thread keyboardThread;
public MainWindow()
{
InitializeComponent();
keyboardThread = new Thread(new ThreadStart(KeyboardThread));
keyboardThread.SetApartmentState(ApartmentState.STA);
keyboardThread.Start();
}
void KeyboardThread()
{
while (true)
{
if (Keyboard.IsKeyDown(Key.A))
{
}
Thread.Sleep(100);
}
}
}
}发布于 2013-10-18 11:14:43
我有一个简单的方法,可以为我处理UI线程上的运行:
public object RunOnUiThread(Delegate method)
{
return Dispatcher.Invoke(DispatcherPriority.Normal, method);
}其中Dispatcher是使用UI线程的Dispatcher.CurrentDispatcher初始化的。它可以从任何线程调用,其用法如下:
UiThreadManager.RunOnUiThread((Action)delegate
{
// running on the UI thread
});https://stackoverflow.com/questions/19448141
复制相似问题