开发者

C#: Windows Forms: Getting keystrokes in a panel/picturebox?

开发者 https://www.devze.com 2022-12-27 19:41 出处:网络
I\'m making a level editor for a game using windows forms. The form has several drop down menus, text boxes, etc, where the user can type information.

I'm making a level editor for a game using windows forms. The form has several drop down menus, text boxes, etc, where the user can type information.

I want to make commands like CTRL + V or CTRL + A available for working within the game world itself, not text manipulation. The game world is represented by a PictureBox contained in a Panel.

This event handler isn't ever firing:

private System.Windows.Forms.Panel canvas;
// ...
this.canvas = new System.Windows.Forms.Panel();
// ...
this.canvas.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.canvas_PreviewKeyDown);

What is the preferred way of doing this? Can a panel even receive keyboard input? I would like to allow the user to use copy/paste/select-all commands when working with the 开发者_开发问答text input, but not when placing objects in the game world.


From the MSDN documentation for Control.CanSelect:

The Windows Forms controls in the following list are not selectable and will return a value of false for the CanSelect property. Controls derived from these controls are also not selectable.

  • Panel
  • GroupBox
  • PictureBox
  • ProgressBar
  • Splitter
  • Label
  • LinkLabel (when there is no link present in the control)

Although it says controls derived from these controls cannot receive focus, you can create a derived control and use the SetStyle method to enable the "Selectable" style. You also must set the TabStop property to true in order for this to work.

public class SelectablePanel : Panel
{
    public SelectablePanel()
    {
        this.SetStyle(ControlStyles.Selectable, true);
        this.TabStop = true;
    }
}

Then use this control instead of the normal Panel. You can handle the PreviewKeyDown event as intended.


You'll probably want to do the key capture at the form level. This is highly recommended reading from the person who helped write the underlying .NET code:

http://blogs.msdn.com/jfoscoding/archive/2005/01/24/359334.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号