如何使图片框可选?

10 user-interface winforms

我正在制作一个非常基本的地图编辑器.我已经完成了一半,我遇到的一个问题是如何删除一个对象.

我想按删除但似乎没有图片框的keydown事件,看起来我将只在我的列表框上.

在我的编辑器中删除对象的最佳解决方案是什么?

Han*_*ant 18

您将希望PictureBox参与Tab键顺序并显示它具有焦点.这需要一些小手术.在项目中添加一个新类并粘贴下面显示的代码.编译.将新控件从工具箱顶部拖放到表单上.实现KeyDown事件.

using System;
using System.Drawing;
using System.Windows.Forms;

class SelectablePictureBox : PictureBox {
  public SelectablePictureBox() {
    this.SetStyle(ControlStyles.Selectable, true);
    this.TabStop = true;
  }
  protected override void OnMouseDown(MouseEventArgs e) {
    this.Focus();
    base.OnMouseDown(e);
  }
  protected override void OnEnter(EventArgs e) {
    this.Invalidate();
    base.OnEnter(e);
  }
  protected override void OnLeave(EventArgs e) {
    this.Invalidate();
    base.OnLeave(e);
  }
  protected override void OnPaint(PaintEventArgs pe) {
    base.OnPaint(pe);
    if (this.Focused) {
      var rc = this.ClientRectangle;
      rc.Inflate(-2, -2);
      ControlPaint.DrawFocusRectangle(pe.Graphics, rc);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)