所以我有一个庞大的程序,我决定让其中一个方法在单独的线程中运行。所以我把这个方法放在一个单独的类中,并在我的表单上激活它。它似乎按照我想要的方式工作,直到它到达它给了我这个错误的地方:
SendKeys cannot run inside this application because the application is not handling Windows messages. Either change the application to handle messages, or use the SendKeys.SendWait method.
我试着在网上寻找答案。我想我看到了一些关于 SendKeys 如何仅在 Form 或其他东西中工作的信息。
谁能告诉我不使用 SendKeys 模拟击键的方法,或者让 SendKeys 在不同的非表单线程中工作的方法?
最佳答案
您的控制台应用程序需要一个消息循环。这是通过 Application 完成的类(class)。您需要调用 Application.Run(ApplicationContext) .
class MyApplicationContext : ApplicationContext
{
[STAThread]
static void Main(string[] args)
{
// Create the MyApplicationContext, that derives from ApplicationContext,
// that manages when the application should exit.
MyApplicationContext context = new MyApplicationContext();
// Run the application with the specific context. It will exit when
// the task completes and calls Exit().
Application.Run(context);
}
Task backgroundTask;
// This is the constructor of the ApplicationContext, we do not want to
// block here.
private MyApplicationContext()
{
backgroundTask = Task.Factory.StartNew(BackgroundTask);
backgroundTask.ContinueWith(TaskComplete);
}
// This will allow the Application.Run(context) in the main function to
// unblock.
private void TaskComplete(Task src)
{
this.ExitThread();
}
//Perform your actual work here.
private void BackgroundTask()
{
//Stuff
SendKeys.Send("{RIGHT}");
//More stuff here
}
}
关于c# - 如何在非表单应用程序中生成击键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10057608/