开发者

How do i make a picturebox selectable?

I am making a very basic map editor. I'm halfway through it and one problem i hit is how to delete an object.

I would like to press delete but there appears to be no keydown event for pictureboxes and it will seem like i will have it only on my listbox.

What is the best solution for deleting 开发者_Go百科an object in my editor?


You'll want the PictureBox to participate in the tabbing order and show that it has the focus. That takes a bit of minor surgery. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form. Implement the KeyDown event.

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);
    }
  }
}


i think this is the best methode:

http://felix.pastebin.com/Q0YbMt22


... 8 years after ...

An alternative to Hans Passant's code, which doesn't require you to create a new class just so your PictureBox is in the tab order, is to set TabStop to true, and call SetStyle() directly on the PictureBox, optimally after InitializeComponent() is called.

TabStop is public, so it's easily set, but SetStyle() is protected, so reflection comes to the rescue!

myPictureBox.TabStop = true;
typeof(PictureBox)
    .GetMethod("SetStyle", BindingFlags.Instance | BindingFlags.NonPublic)
    .Invoke(myPictureBox, new object[] { ControlStyles.Selectable, true });

This of course, doesn't do anything like getting the focus when the PictureBox is clicked, so you have to do that in its various events as you see fit.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜