我正在尝试模拟键盘输入,以便以编程方式在VisualBoy Advance中玩游戏。使用SendKeys.SendWait()时,VisualBoy Advance没有响应。
private const string VBA_PROCESS_NAME = "VBA-rr-svn480";
public void Up()
{
PressButton("{UP}");
}
public void Down()
{
PressButton("{DOWN}");
}
public void Left()
{
PressButton("{LEFT}");
}
public void Right()
{
PressButton("{RIGHT}");
}
public void A()
{
PressButton("z");
}
public void B()
{
PressButton("x");
}
public void LShoulder()
{
PressButton("a");
}
public void RShoulder()
{
PressButton("s");
}
public void Start()
{
PressButton("~");
}
public void Select()
{
PressButton("+");
}
private void PressButton(string Button)
{
var VBAProcess = GetVBAProcess();
// Verify that VBA is a running process.
if (VBAProcess == null)
throw new Exception("Visual Boy Advance could not be found.");
IntPtr VBAHandle = VBAProcess.MainWindowHandle;
// Make sure that VBA is running and that we have a valid handle.
if (VBAHandle == IntPtr.Zero)
throw new Exception("Visual Boy Advance is not running.");
// Make VBA the foreground application and send it the button press.
SetForegroundWindow(VBAHandle);
SendKeys.SendWait(Button);
}
// Activate an application window.
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
private Process GetVBAProcess()
{
return Process.GetProcessesByName(VBA_PROCESS_NAME).FirstOrDefault();
}
如果我将进程名称换成其他进程(例如notepad ++),则按键会正常工作。这使我相信,对于VisualBoy Advance,我必须使用错误的进程或窗口,但是当我抓住所有进程并仔细查看它们时,我没有找到看起来正确的进程。