Question

I am trying to make a tool that allows me to choose a certain location on a picturebox to put text from a textbox on. It will need to be able to place multiple different texts on the picturebox and then be able to be deleted. This is my current code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TextboxTool
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            pictureBox1.Image = new Bitmap(pictureBox1.Width, pictureBox1.Height);
        }

        private void textBox1_MouseClick(object sender, MouseEventArgs e)
        {
            textBox1.Text = "";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Visible = true;
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            Graphics G = Graphics.FromImage(pictureBox1.Image);
            G.DrawString(textBox1.Text, new Font("Tahoma", 40), Brushes.Black, new Point(MousePosition.X, MousePosition.Y));
        }
    }
}

At the moment i can type the text in the textbox, but can't draw the string on the picturebox and choose its location. I have a button which is meant to confirm the text written is right and then allow the user to choose its location. Please can someone help me sort this code out?

Thanks-

Was it helpful?

Solution

The MousePosition property is relative to the screen, not the PictureBox.

You should handle the MouseClick event and draw the string at e.X and e.Y.
Alternatively, you can call pictureBox1.PointToClient to transform screen coordinates to control-relative coordinates.

Also, you should dispose the Graphics object in a using statement.

Finally, I'm pretty sure you'll need to call pictureBox1.Invalidate() after modifying the image to force it to repaint.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top