我剛啟動 C#,我想制作一個表單應用程序,它在 TextBox 中從用戶那里獲取密鑰,然后以某種方式綁定該密鑰并使用 SendKeys(),向我在代碼 eg(e) 中設置的特定密鑰發送垃圾郵件,我使用這段代碼但是Keyboard.isKeyDown(Key.key)想要我一個“Key”的枚舉,TexBox 返回一個字符串,甚至我將字符串轉換為一個枚舉,但它只想要我一個來自它自己的Key枚舉的鍵,我的問題是如何將一個變量鍵傳遞給Keyboard.isKeyDown(Key.key)maybe完全我的方法不對,你能幫我處理這些代碼或建議另一種方法來制作這個應用程序嗎?這是代碼:using System;using System.Windows.Forms;using System.Windows.Input;using System.Threading;using System.Runtime.InteropServices;namespace WindowsFormsApp1{ public partial class Form1 : Form { [DllImport("USER32.DLL", CharSet = CharSet.Unicode)] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("USER32.DLL")] public static extern bool SetForegroundWindow(IntPtr hWnd); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { Thread TH = new Thread(PressBind); TH.SetApartmentState(ApartmentState.STA); CheckForIllegalCrossThreadCalls = false; TH.Start(); } //i want to get the key from this textbox public void TxBxKTB_TextChanged(object sender, EventArgs e) { label2.Text = $"The binded key is : {TxBxKTB.Text.ToString()}"; TextBox objTextBox = (TextBox)sender; string text = objTextBox.Text; var TextBoxText = Enum.Parse(typeof(Keys), text); }
1 回答
GCT1015
TA貢獻1827條經驗 獲得超4個贊
更新
您可以使用Enum.Parse方法將字符串轉換為Key枚舉。使用它TryParse來處理無法將字符串轉換為Key.
void Z()
{
? ? string key_string = "F10";
? ? if (Enum.TryParse(key_string, out Key key))
? ? {
? ? ? ? if (Keyboard.IsKeyDown(key))
? ? ? ? {
? ? ? ? ? ? // some logic
? ? ? ? }
? ? }
? ? else
? ? {
? ? ? ? // ERROR: the string couldn't be converted to Key
? ? }
}
- 1 回答
- 0 關注
- 199 瀏覽
添加回答
舉報
0/150
提交
取消
