c# - 如何在非表单应用程序中生成击键

标签 c# multithreading automation sendkeys

所以我有一个庞大的程序,我决定让其中一个方法在单独的线程中运行。所以我把这个方法放在一个单独的类中,并在我的表单上激活它。它似乎按照我想要的方式工作,直到它到达它给了我这个错误的地方:

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/

相关文章:

c# - Windows 窗体应用程序中不同线程中的 GUI 和逻辑分离

java - 中断正在运行的线程

go - Chromedp 不在 ActionFunc 的循环内执行操作

c# - Process.Start() 无法打开 exe

c# - RAM 性能基准测试 - UWP 和 C#

Java并发实践: Listing 8. 3.引入锁顺序以防止死锁

c# - Word 自动化 : Detect if page break is necessary?

c# - 当使用 Microsoft.Office.Interop.Word 将 html 转换为 Word 时,字体大小不一样

c# - SharePoint checkin SPListItem

python - 带有 python 自动电子邮件通知的测试框架