drawstring onclick method C#
-
20-06-2021 - |
Question
I have some strings that I have drawn using DrawString
for (int j = 0; j < dt.Rows.Count; j++)
{
e.Graphics.DrawString(Convert.ToString(dt.Rows[j]["ID"]), drawFont, drawBrush, new Point(Convert.ToInt32(dt.Rows[j]["XCord"]), Convert.ToInt32(dt.Rows[j]["YCord"])));
}
Is there any way to create an onclick event for each drawstring? I was hoping to create a new form when you clicked on the drawstring. Thanks!
Solution
Handle the MouseClick
event of the container and enumerate through the rows to find out the "rectangle" of the text and see if the mouse location is inside it:
void panel1_MouseClick(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
foreach (DataRow dr in dt.Rows) {
Point p = new Point(Convert.ToInt32(dr["XCord"]), Convert.ToInt32(dr["YCord"]));
Size s = TextRenderer.MeasureText(dr["ID"].ToString(), panel1.Font);
if (new Rectangle(p, s).Contains(e.Location)) {
MessageBox.Show("Clicked on " + dr["ID"].ToString());
}
}
}
}
OTHER TIPS
No. When you render things with Graphics
you can not bind events to the drawn object.
There are two solutions, you could catch mouse clicks on the form (MouseClick
event) and determine if the mouse is over a rendered string (getting the render area using MeasureString
). This, however, is unnecessarily difficult and complex.
Instead, I recommended spawning a control dynamically on the form. You could spawn a Button
or, if you like the style of just the text on the form, a Label
and then bind an EventHandler to their MouseClick
event.