System.Windows.Forms.SendKeys 類別提供將按鍵訊息送入作業系統訊息佇列的功能,常用於自動化測試、巨集腳本或舊系統整合。本文以「魔獸世界自動登入器」為實戰案例,完整示範從設定檔讀取帳密、啟動遊戲、等待畫面載入、模擬輸入帳號密碼並按 Enter 的完整流程。
[Serializable]
public class ViaStruct
{
public string Timer { get; set; } // 開機後等待分鐘數
public string FilePath { get; set; } // 遊戲執行檔路徑
public string UserName { get; set; }
public string Pwd { get; set; }
public string Timer2 { get; set; } // 啟動遊戲後等待分鐘數
public bool SuccessFlag { get; private set; }
public ViaStruct() => SuccessFlag = ReadFromFile();
private bool ReadFromFile()
{
try
{
using (var sr = new StreamReader("info.txt"))
{
FilePath = sr.ReadLine() ?? "";
if (string.IsNullOrEmpty(FilePath)) return false;
Timer = sr.ReadLine() ?? "";
Timer2 = sr.ReadLine() ?? "";
UserName = sr.ReadLine() ?? "";
Pwd = sr.ReadLine() ?? "";
}
return true;
}
catch { return false; }
}
public void WriteToFile()
{
Task.Run(() =>
{
try
{
using (var sw = new StreamWriter("info.txt"))
{
sw.WriteLine(FilePath);
sw.WriteLine(Timer);
sw.WriteLine(Timer2);
sw.WriteLine(UserName);
sw.WriteLine(Pwd);
}
MessageBox.Show("寫入成功!");
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
});
}
}
public partial class Form1 : Form
{
private readonly ViaStruct _via = new ViaStruct();
private Thread _scheduleThread;
public Form1()
{
InitializeComponent();
Load += Form1_Load;
FormClosing += Form1_FormClosing;
}
private void Form1_Load(object sender, EventArgs e)
{
txtUser.Text = _via.UserName;
txtPwd.Text = _via.Pwd;
txtPath.Text = _via.FilePath;
txtWait2.Text = _via.Timer2;
cboWait1.Text = _via.Timer;
_scheduleThread = new Thread(RunSchedule) { IsBackground = true };
_scheduleThread.Start();
}
private void RunSchedule()
{
if (!_via.SuccessFlag) return;
try
{
Thread.Sleep(TimeSpan.FromMinutes(double.Parse(_via.Timer)));
Process.Start(_via.FilePath);
Thread.Sleep(TimeSpan.FromMinutes(double.Parse(_via.Timer2)));
}
catch (ThreadAbortException) { return; }
catch (Exception ex) { MessageBox.Show(ex.Message); return; }
SendKeysInput();
}
private void SendKeysInput()
{
foreach (char c in _via.UserName)
{
SendKeys.SendWait(c.ToString());
Thread.Sleep(10);
}
SendKeys.SendWait("{TAB}");
foreach (char c in _via.Pwd)
{
SendKeys.SendWait(c.ToString());
Thread.Sleep(10);
}
SendKeys.SendWait("{ENTER}");
}
// ... 按鈕事件:選擇路徑、儲存設定、立即執行、最小化至系統匣 ...
}
| 按鍵 | SendKeys 代碼 |
|---|---|
| Enter | {ENTER} |
| Tab | {TAB} |
| Shift+Tab | +{TAB} 或 {BACKTAB} |
| Esc | {ESC} |
| F1~F12 | {F1} ~ {F12} |
| Home / End | {HOME} / {END} |
| PgUp / PgDn | {PGUP} / {PGDN} |
| Del / Backspace | {DEL} / {BACKSPACE} |
| 方向鍵 | {LEFT} {RIGHT} {UP} {DOWN} |
| Ctrl+鍵 | ^c (Ctrl+C)、^v (Ctrl+V) |
| Alt+鍵 | %f (Alt+F) |
| Shift+鍵 | +a (Shift+A = 大寫 A) |
| 特殊符號 | +1=! +2=@ +3=# +4=$ +5=% +6=^ +7=& +8=* +9=( +0=) +==+ +`=~ |
SendKeys 可能被攔截或導致封號,僅供教學參考。WindowsInput (NuGet) — 可指定目標視窗控制元素,不依賴前景視窗。