Popping up a TextBox on mouse click over a PictureBox for adding custom note to picture

时光总嘲笑我的痴心妄想 提交于 2019-12-08 21:24:37

You could embed a control in a custom popup form, as shown below.

The last argument in the PopupForm constructor specifies the action to take, when the user presses Enter. In this example an anonymous method is specified, setting the title of the form.

Usage

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
  // in this case we create a TextBox, but the
  // PopupForm can hold any type of control.
  TextBox textBox = new TextBox();
  Point location = pictureBox1.PointToScreen(e.Location);
  PopupForm form = new PopupForm(textBox, location,
    () => this.Text = textBox.Text);
  form.Show();
}

PopupForm Class

public class PopupForm : Form
{
  private Action _onAccept;
  private Control _control;
  private Point _point;

  public PopupForm(Control control, int x, int y, Action onAccept)
    : this(control, new Point(x, y), onAccept)
  {
  }

  public PopupForm(Control control, Point point, Action onAccept)
  {
    if (control == null) throw new ArgumentNullException("control");

    this.FormBorderStyle = FormBorderStyle.None;
    this.ShowInTaskbar = false;
    this.KeyPreview = true;
    _point = point;
    _control = control;
    _onAccept = onAccept;
  }

  protected override void OnLoad(EventArgs e)
  {
    base.OnLoad(e);
    this.Controls.Add(_control);
    _control.Location = new Point(0, 0);
    this.Size = _control.Size;
    this.Location = _point;
  }

  protected override void OnKeyDown(KeyEventArgs e)
  {
    base.OnKeyDown(e);
    if (e.KeyCode == Keys.Enter)
    {
      _onAccept();
      this.Close();
    }
    else if (e.KeyCode == Keys.Escape)
    {
      this.Close();
    }
  }

  protected override void OnDeactivate(EventArgs e)
  {
    base.OnDeactivate(e);
    this.Close();
  }
}

I suppose, you could create Textbox dynamically on mouse click and use it's BringToFront() method in case is will not appear above the picture box. When the user presses Enter, handle this event, get text from Textbox and remove if if needed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!