Creating clickable C# image map in winforms

余生颓废 提交于 2020-02-02 12:31:17

问题


I'm trying to develop a basic C# winforms app with a clickable image map as its focus. That is, an image where a certain section is clickable and will open a new form. For example the image could be a chessboard, and clicking on a certain square will perform the action of opening a new form.

I hope this concept is clear. I've looked at similar questions on S.O. and could not find a workable solution.

Cheers


回答1:


My solution would be to leverage the MouseUp event on whatever control holds the image. When you get that click, resolve the position of e.Location (MouseUp gives you MouseEventArgs) down to the control using PointToClient().

Once you have that Point, you need only determine if it's in a valid Rectangle, and if it is, launch the appropriate form.

Edit:

You can use the forms designer to add a control to the form, such as a Panel and then add an event handler to that control, such as OnMouseUp. It would look something like this:

private void panel1_MouseUp(Object sender, MouseEventArgs e)
{
    //your code goes here
}

That event handler will be called whenever the user clicks on your panel and releases the mouse button.

In that event handler, you could have something like this:

if (e.Button.Equals(MouseButtons.Left))
{
    Rectangle rect = new Rectangle(10, 10, 100, 100);  //this is the zone you wish to react the user clicking on
    if (rect.Contains(e.Location))
    {
        //show your form
    }
}

e.Location is going to be the location of the mouse at the moment the button was released, in coordinates corresponding to the control in question, in this case panel1.

You will probably want a more elegant solution if there are many regions to consider, such as keeping a list or array of Rectangle and looping over them.




回答2:


Basically you would handle the click event on the image and get the coordinates of the click point. Then you have to evaluate it to the values you need in order to do something or not.

Alternatively you could use "zones".

There is already a similar q&a that could be what you're looking for:

Create clickable zones in image?

Edit:

There is an image-map control project on codeproject at the following url:

http://www.codeproject.com/Articles/2820/C-Windows-Forms-ImageMap-Control

Although it's .NET 1.0, it shouldn't be a big deal to adapt it to your needs.



来源:https://stackoverflow.com/questions/21286617/creating-clickable-c-sharp-image-map-in-winforms

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