问题
In my C# winforms application, I have a picturebox which some bitmap images can be loaded into it. What I want to do is if user clicks somewhere within picturebox, at the mouse location a small textbox will be appeared and user can add a custom text (note) to the picture.
I know how to write a string into a bitmap file, but I couldnt find a way to POP UP a textbox at mouse location, and automaticly add the text to the image when user wrote something and hit enter key. How this textbox and its properties should be defined?
Thanks.
回答1:
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();
}
}
回答2:
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.
来源:https://stackoverflow.com/questions/5549150/popping-up-a-textbox-on-mouse-click-over-a-picturebox-for-adding-custom-note-to