簡體   English   中英

C#SendKey循環卡住了

[英]C# SendKey loop stuck

因此,我一直在嘗試使用帶有for循環的SendKey.Send方法,由於某種原因,只有當我在其中使用它時,它才會陷入無限循環。 我嘗試了沒有它的代碼,由於某種原因它起作用了。

    private void button1_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < trackBar2.Value; i++)
        {
            SendKeys.Send("{ENTER}");
            System.Threading.Thread.Sleep(trackBar1.Value);
        }
    }

似乎是什么問題?

*編輯:不能是“ Enter”鍵,因為它與其他鍵和字符串具有相同的作用,例如:

SendKey.Send("a");

按下button1,這時將執行顯示的代碼。 然后將Enter發送到button1(因為它仍然具有焦點),導致該代碼再次運行,依此類推。

因此,您已經創建了一個循環。

如果嘗試發送其他密鑰(例如a ,則由於Thread.Sleep ,該程序將掛起一會兒,但之后應再次響應。

您可以嘗試運行SendKeys.Send("{ENTER}");SendKeys.Send("{ENTER}"); 在后台線程中。 我不確定為什么它阻塞了您的主線程,但是以下方法有效。

  static void Main()
    {
        // setup some form state
        Form form = new Form();

        BackgroundWorker worker = new BackgroundWorker();
        worker.WorkerReportsProgress = true;

        // start the worker when the form loads
        form.Load += delegate
        {
            worker.RunWorkerAsync();
        };
        worker.DoWork += delegate
        {
            // this code happens on a background thread, so doesn't
            // block the UI while running - but shouldn't talk
            // directly to any controls
            for (int i = 0; i < 500; i++)
            {
                worker.ReportProgress(0, "Item " + i);
                Thread.Sleep(150);
            }
        };
        worker.ProgressChanged += delegate(object sender,
           ProgressChangedEventArgs args)
        {
            SendKeys.Send("{Enter}");
        };
        Application.Run(form);
    }

經過五百次迭代后,我的應用程序回復了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM