问题描述
我使用的是 Visual Studio 2019,我的问题与此 Tutorial 的使用密切相关。我已经完成了所有步骤,例如:
我的问题:我错过了什么?我无法访问游戏杆库 Screenshot of Error
这里是完整的 Form1.cs 代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RunJoyStickOnLocalMachine{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender,EventArgs e)
{
}
private void joystickTimer_Tick_1(object sender,EventArgs e)
{
try
{
joystick.UpdateStatus();
joystickButtons = joystick.buttons;
if (joystick.Xaxis == 0)
output.Text += "Left\n";
if (joystick.Xaxis == 65535)
output.Text += "Right\n";
if (joystick.Yaxis == 0)
output.Text += "Up\n";
if (joystick.Yaxis == 65535)
output.Text += "Down\n";
for (int i = 0; i < joystickButtons.Length; i++)
{
if (joystickButtons[i] == true)
output.Text += "Button " + i + " pressed\n";
}
}
catch
{
joystickTimer.Enabled = false;
connectToJoystick(joystick);
}
}
}
}
如果还有什么需要我提供的,请通知我。
谢谢!
编辑:我通过比较教程文件和博客的分步教程文件解决了这个问题。
解决方法
您可以从您提到的文章中下载项目以检查代码。
根据我的测试,在项目中添加theJoystick.cs
后,可以在form1.cs代码中使用如下代码。
public partial class Form1 : Form
{
private Joystick joystick; // define the type Joystick
private bool[] joystickButtons; // here define the bool array
public Form1()
{
InitializeComponent();
joystick = new Joystick(this.Handle);
connectToJoystick(joystick);
}
private void joystickTimer_Tick(object sender,EventArgs e)
{
try
{
joystick.UpdateStatus();
joystickButtons = joystick.buttons;
if (joystick.Xaxis == 0)
output.Text += "Left\n"; // output is the name of richtextbox
if (joystick.Xaxis == 65535)
output.Text += "Right\n";
if (joystick.Yaxis == 0)
output.Text += "Up\n";
if (joystick.Yaxis == 65535)
output.Text += "Down\n";
for (int i = 0; i < joystickButtons.Length; i++)
{
if (joystickButtons[i] == true)
output.Text += "Button " + i + " Pressed\n";
}
}
catch
{
joystickTimer.Enabled = false;
connectToJoystick(joystick);
}
}
private void enableTimer()
{
if (this.InvokeRequired)
{
BeginInvoke(new ThreadStart(delegate ()
{
joystickTimer.Enabled = true;
}));
}
else
joystickTimer.Enabled = true;
}
private void connectToJoystick(Joystick joystick)
{
while (true)
{
string sticks = joystick.FindJoysticks();
if (sticks != null)
{
if (joystick.AcquireJoystick(sticks))
{
enableTimer();
break;
}
}
}
}
}