我正在撰寫一個需要在后臺監控按鍵的應用程式。這是我正在使用的當前代碼,我嘗試了許多不同的方法來檢測按鍵并使用斷點進行除錯,但均未成功。我應該提一下(如果不是很明顯),我是異步編程的新手,我仍然只在非常低的層次上理解它。
private async void Form2_Load(object sender, EventArgs e)
{
await KeyboardPressSearch();
}
private static async Task<bool> KeyboardPressSearch()
{
await Task.Delay(5000);
while (true)
{
if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift)
{
var p = new Process();
p.StartInfo.FileName = @"C:\Program Files\REAPER (x64)\reaper.exe";
p.Start();
return true;
}
}
}
你會建議我做什么或改變什么?謝謝你。
uj5u.com熱心網友回復:
正如 Theodor Zoulias 在評論中提到的,您可以通過設定和注冊事件Form.KeyPreview
來實作此行為。true
KeyPress
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.ShiftKey)
{
var p = new Process();
p.StartInfo.FileName = @"C:\Program Files\REAPER (x64)\reaper.exe";
p.Start();
//e.Handled = true if you don't want the other controls to see this keypress
e.Handled = true;
}
}
該代碼現在根據定義將是異步的,因為它不會等到按鍵按下,而是對其做出反應。如果您確實需要await
某個Task
物件,一旦滿足此事件的條件,該物件將完成,請使用TaskCompletionSource
:
public Task KeyboardPressSearch()
{
// Invoking is used so that localFunc() is always executed on the UI thread.
// locks or atomic operations can be used instead
return
InvokeRequired
? Invoke(localFunc)
: localFunc();
Task localFunc()
{
taskCompletionSource ??= new();
return taskCompletionSource.Task;
}
}
private TaskCompletionSource? taskCompletionSource;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.ShiftKey)
{
var p = new Process();
p.StartInfo.FileName = @"C:\Program Files\REAPER (x64)\reaper.exe";
p.Start();
//e.Handled = true if you don't want the other controls to see this keypress
e.Handled = true;
if(taskCompletionSource is not null)
{
taskCompletionSource.SetResult();
taskCompletionSource = null;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/469324.html