I'm currently working on a little game as a WinForms project. The gamefield is build out of a grid of Tiles a Player (a separate class) can move on. I want the player to move with the arrow keys and have set up an event handler for it, but it doesn't seem to be ever called.
(minimalized) player class, which implements the System.Windows.Forms packages for the KeyEventArgs:
public class Player : MovableObject
{
public Player(Playtile position) : base(position)
{
EntityColor = ElementColors.PlayerColor;
PostConstructor(position);
}
/// <summary>
/// Reads keypress via eventhandler KeyEventArgs (key down).
/// </summary>
private void ReadKeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Up:
// move up.
break;
case Keys.Right:
// move right.
break;
case Keys.Down:
// move down.
break;
case Keys.Left:
// move left.
break;
}
}
}
Currently, the ReadKeyDown never gets called. How do I actually assign / bind that KeyEventDown event to the player, so it actually calls that method on key down?
KeyEventArgs in C# seems to simply say this.KeyDown += ReadKeyDown;
, but it doesn't recognize KeyDown as anything, nor does it give me a possible missing assembly reference.
KeyDown
is a member of Control
so in your case you could subscribe to that event in your Form
.
Like the following:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
textBox1.KeyDown += TextBox1_KeyDown;
}
private void TextBox1_KeyDown(object sender, KeyEventArgs e)
{
}
}
See the official documentation for a complete example:
Now what you could do is invoke a method in your target class once you've received such event:
public class MyClass
{
public void OnKeyDown(KeyEventArgs e)
{
// ...
}
}
public partial class Form2 : Form
{
MyClass _instance = new MyClass();
public Form2()
{
InitializeComponent();
textBox1.KeyDown += TextBox1_KeyDown;
}
private void TextBox1_KeyDown(object sender, KeyEventArgs e)
{
_instance.OnKeyDown(e);
}
}