Reputation: 10412
I'm sorry if this has been asked before, I tried to search and didn't find anything.
I am creating a C# WPF application.
I have an image, for example of a man.
Is there a way to detect which part of the man's body the mouse has clicked? for example if the mouse clicks his hand we get a message box : "You have clicked the hand"?
I would like to divide the into random shapes not just rectangles, so the mouse click have to be precise.
Thanks a lot for any help
Upvotes: 1
Views: 1399
Reputation: 31841
Sure, no problem.
With XAML like this:
<Border BorderBrush="Gray"
BorderThickness="1"
Height="200" Width="200"
MouseMove="Border_MouseMove">
<TextBlock Name="Jerry" />
</Border>
Do something like this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Border_MouseMove(object sender, MouseEventArgs e)
{
var _Control = (sender as System.Windows.Controls.Border);
var _ControlLocation = _Control.PointToScreen(new Point(0, 0));
var _MousePosition = MouseInfo.GetMousePosition();
var _RelativeLocation = _MousePosition - _ControlLocation;
this.Jerry.Text = _RelativeLocation.ToString();
}
}
internal class MouseInfo
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
[return: System.Runtime.InteropServices.MarshalAs(
System.Runtime.InteropServices.UnmanagedType.Bool)]
internal static extern bool GetCursorPos(ref Win32Point pt);
[System.Runtime.InteropServices.StructLayout(
System.Runtime.InteropServices.LayoutKind.Sequential)]
internal struct Win32Point
{
public Int32 X;
public Int32 Y;
};
public static Point GetMousePosition()
{
Win32Point w32Mouse = new Win32Point();
GetCursorPos(ref w32Mouse);
return new Point(w32Mouse.X, w32Mouse.Y);
}
}
I lifted a little code from: Location of WPF control in window? Clearly you want to use something different than a Border - you want an Image. And you want MouseDown instead of MouseMove. But this is the logic you need!
To make this work, it is going to be up to you to know the X and Y on your custom image (like, where the "head" or "arm" is). You'll want to calculate a polygon if the sections are not rectangles. If they are, then this should get you 90% of the way.
Best of luck!
Upvotes: 2
Reputation: 599
You could crop the image into separate pieces and then load them into the window as if it was a complete image. It's not the most effective way, and it only works for static images (a flash video would be perfect for animated "images"), but it can be implemented quickly and easily. If you were to use HTML, the window would have to use the web browser toolbox item (unless you code your own somehow).
Upvotes: 1
Reputation: 27638
If I were you, I'd create multiple polys over the top of the image and get it to the correct position/shape, then make them transparent and handle click events for each poly.
Upvotes: 3