如何生成在非窗体应用程序按键 [英] How do I generate keystrokes in a non-form application

查看:202
本文介绍了如何生成在非窗体应用程序按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个庞大的计划,决定我应该做的在一个单独的线程中运行的方法之一。所以,我把方法一个单独的类,活化它的窗体上。似乎它给了我这个错误,只是工作,我怎么想它,直到它得到了栏目:

So I have a huge program and decided I should make one of the methods run in a separate thread. So I put the method in a separate class, an activated it on my form. It seemed to worked just how I wanted it to until it got to part where it gave me this error:

的SendKeys无法在此应用程序中,因为应用程序不处理Windows消息运行。要么修改应用程序来处理邮件,或使用SendKeys.SendWait方法。

"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只在一个表格什么的工作。

I tried looking for the answer online. I think I saw something about how SendKeys only works in a Form or something.

我的问题是:谁能告诉我一个方法来模拟一个按键,而无需使用的SendKeys,或一种方式来获得的SendKeys在一个不同的,非形式线程的工作。

My question is: Can anyone tell me a way to simulate a keystroke without using SendKeys, OR a way to get SendKeys to work in a different, non-form thread?

推荐答案

您控制台应用程序需要一个消息循环。这是通过应用程序类来完成。您将需要调用 Application.Run(ApplicationContext的)

Your console application needs a message loop. This is done through the Application class. You will need to call 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
    }
}

这篇关于如何生成在非窗体应用程序按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆