In HTML pages, many of us saw click-able HTML transparent map areas which show some tip or have a hyperlink. We can achieve the same thing in Windows application where we can handle the click and do whatever necessary.
How this can be done? Let us take the simple
Panel
control which has device context and fire click event. The simplicity of this control is useful. In html map complex area are defined by set of coordinate pairs. Here we can have that by using the
GrpahicsPath
from
System.Drawing.Drawing2D
. Then we can set the
Region
of the panel to this graphics path. Make the
background color
of the panel to
Transparent
. Now the panel is ready and we can add this to the controls collection of the picture box, position it using the location property of the panel.
Here is the code. I use a custom panel class to draw the panel in the picture box.
class CirclePanel:Panel
{
float radius;
public float Radius
{
get { return radius; }
set
{
radius=value;
this.Size = new Size((int)Radius, (int)Radius);
}
}
Point centre;
public Point Centre
{
get { return centre; }
set
{
centre=value;
this.Location = Centre;
}
}
public string Message { get; set; }
public CirclePanel()
{
this.BackColor = Color.Transparent;
Radius = 1;
Centre = new Point(0, 0);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (centre != null)
{
GraphicsPath path = new GraphicsPath();
path.AddEllipse(0, 0, radius, radius);
this.Region = new Region(path);
path.Dispose();
}
}
}
Now how to use this class:
private void Form2_Load(object sender, EventArgs e)
{
CirclePanel panel2 = new CirclePanel();
panel2.Centre = new Point(100, 100);
panel2.Radius = 50;
panel2.Message = "you clicked Me";
pictureBox1.Controls.Add(panel2);
panel2.Click += new EventHandler(panel2_Click);
}
protected void panel2_Click(object sender, EventArgs e)
{
CirclePanel panel = (CirclePanel)sender;
MessageBox.Show(panel.Message);
}
This example will plot a transparent click-able area at 100x, 100y point with radius of 50 pixels. The click event can be handled. This technique may be useful for fancy UI, Interactive display like maps, etc.