Passing a point collection to visual HitTest - wpf

Can I pass a collection of locations to HitTest(object, location). I have a line for an object and a points that make the edge of a shape, which are the locations. Is this an efficient way of finding the intersection point?

Insead of a collection of points for the edges of an ellipse, can't you use an EllipseGeometry?
Here is an example
void SomeControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
UIElement element = sender as UIElement;
Point point = e.GetPosition(element);
EllipseGeometry hitGeometry = new EllipseGeometry(point, 1.0, 1.0);
VisualTreeHelper.HitTest(element,
null,
new HitTestResultCallback(HitTestCallback),
new GeometryHitTestParameters(hitGeometry));
}
public HitTestResultBehavior HitTestCallback(HitTestResult result)
{
// Do your hit testing
}

Related

Drawing multiple polygons in canvas

I have a canvas, myCanvas where i want to draw multiple polygons on the location where i specify the points.
PointCollection polygonpoints = new PointCollection();
private void myCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
//add polygon collection
Point p = e.GetPosition(MapGrid);
polygonpoints.Add(p);
}
private void myCanvas_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
Polygon poly = new Polygon();
poly.Points = polygonpoints;
poly.Fill = Brushes.AliceBlue;
MapCanvas.Children.Add(poly);
polygonpoints.Clear(); // this is making clear the polygon but the pointcollection is remain
}
polygonpoints.Clear - i planned to use this for clearing the polygon points for next polygon. but this is not happening.
Any suggestions please.
I believe the issue is you're passing polygonpoints rather than a copy of it as poly.Points.
Change the polygon creation to
Polygon poly = new Polygon
{
Points = new PointCollection(polygonpoints),
Fill = Brushes.AliceBlue
};

Bing map silverlight binding for moving target

I want to animate a "car" dot on a Bing map. I can easily draw multiple dots as the item travels around, but I want to have a single dot move around per car.
XAML
<m:Map Name="myMap" Grid.Row="2" MouseClick="myMap_MouseClick" UseInertia="True">
<m:MapLayer x:Name="carLayer" />
</m:Map>
Some code:
private void AddCarDot(double latitude, double longitude)
{
Ellipse point = new Ellipse();
point.Width = 15;
point.Height = 15;
point.Fill = new SolidColorBrush(Colors.Blue);
point.Opacity = 0.65;
Location location = new Location(latitude, longitude);
MapLayer.SetPosition(point, location);
MapLayer.SetPositionOrigin(point, PositionOrigin.Center);
carLayer.Children.Add(point);
}
private void cmbCar_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(cmbCar.SelectedItem != null)
{
Binding binding = new Binding("CarLocation");
binding.Source = cmbCar.SelectedItem;
binding.Mode = BindingMode.OneWay;
carLayer.SetBinding(MapLayer.PositionProperty, binding);
}
}
The CarLocation is a property on the Car object of type Location.
However that does not work and I'm not quite sure how to get the "car" to move around the map. Can someone point me in the right direction?
Well you're question kind gets cloudly when a mysterious "taxiLayer" appears positively gets muddy when you want set a binding on it instead of the "point" (which I guess represents a car).
What needs to happen is you are using the MapLayer.Position dependency property as an attached property. When the UIElement to which this is attached is a child of a MapLayer map layer knows how to layout it.
So the question is how would assign a binding to this property so that when the value of the bound object changes the position is updated. I'm going to make an assumption the Elipse created in the earlier part of the code is available as field I'll call car. Then the code might look something like this:-
private Elipse AddCarDot(object source)
{
Ellipse point = new Ellipse();
point.Width = 15;
point.Height = 15;
point.Fill = new SolidColorBrush(Colors.Blue);
point.Opacity = 0.65;
MapLayer.SetPositionOrigin(point, PositionOrigin.Center);
point.SetBinding(MapLayer.PositionProperty, new Binding("CarLocation") {Source = source});
carLayer.Children.Add(point);
}
private void cmbCar_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(cmbCar.SelectedItem != null)
{
AddCarDot(cmbCar);
}
}
Now assuming you object that has a CarLocation property implement INotifyPropertyChanged so the binding can be alerted when CarLocation changes the dot will move appropriately.

how to GetMousePosition anywhere on the screen, outside the bounds of window (or any Visual)

I'd like to track the position of the Mouse cursor, in screen coordinates, anywhere on the screen. So even if the mouse cursor moves outside the bounds of the window, is there a way to get the position of the mouse cursor?
What I'm doing is trying to get a popup to follow the mouse cursor, even if it moves off the main window.
Here is a code snippet of what I've tried (and hasn't worked):
private void OnLoaded(object sender, RoutedEventArgs e)
{
bool gotcapture = this.CaptureMouse();
Mouse.AddLostMouseCaptureHandler(this, this.OnMouseLostCapture);
}
Point mouse_position_relative = Mouse.GetPosition(this);
Point mouse_screen_position = popup.PointToScreen(mouse_position_relative);
private void OnMouseLostCapture(object sender, MouseEventArgs e)
{
bool gotcapture = this.CaptureMouse();
this.textblock.Text = "lost capture.";
}
What exactly was your problem?
Wait! There is a way to position a Popup relative to the screen. see PlacementMode.AbsolutePoint
This showed little happy face flying around:
private Popup _popup;
public Window1()
{
InitializeComponent();
this.Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
_popup = new Popup
{
Child = new TextBlock {Text = "=))", Background = Brushes.White},
Placement = PlacementMode.AbsolutePoint,
StaysOpen = true,
IsOpen = true
};
MouseMove += MouseMoveMethod;
CaptureMouse();
}
private void MouseMoveMethod(object sender, MouseEventArgs e)
{
var relativePosition = e.GetPosition(this);
var point= PointToScreen(relativePosition);
_popup.HorizontalOffset = point.X;
_popup.VerticalOffset = point.Y;
}
Never mind, I realized there is no way to position a Popup relative to the screen, only relative to the Visual which contains it.
There are a number of ways to get the screen coordinates of the mouse position outside of a WPF Window. Unfortunately, you'll need to add references to use either of them, but it is possible. You can find examples of them both in #FredrikHedblad's answer to the How do I get the current mouse screen coordinates in WPF? question. Coincidentally, that question was answered a few days before you asked this question and gave up within 21 minutes of asking.

How do I get the current mouse screen coordinates in WPF?

How to get current mouse coordination on the screen?
I know only Mouse.GetPosition() which get mousePosition of element, but I want to get the coordination without using element.
Or in pure WPF use PointToScreen.
Sample helper method:
// Gets the absolute mouse position, relative to screen
Point GetMousePos() => _window.PointToScreen(Mouse.GetPosition(_window));
To follow up on Rachel's answer.
Here's two ways in which you can get Mouse Screen Coordinates in WPF.
1.Using Windows Forms. Add a reference to System.Windows.Forms
public static Point GetMousePositionWindowsForms()
{
var point = Control.MousePosition;
return new Point(point.X, point.Y);
}
2.Using Win32
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetCursorPos(ref Win32Point pt);
[StructLayout(LayoutKind.Sequential)]
internal struct Win32Point
{
public Int32 X;
public Int32 Y;
};
public static Point GetMousePosition()
{
var w32Mouse = new Win32Point();
GetCursorPos(ref w32Mouse);
return new Point(w32Mouse.X, w32Mouse.Y);
}
Do you want coordinates relative to the screen or the application?
If it's within the application just use:
Mouse.GetPosition(Application.Current.MainWindow);
If not, I believe you can add a reference to System.Windows.Forms and use:
System.Windows.Forms.Control.MousePosition;
If you try a lot of these answers out on different resolutions, computers with multiple monitors, etc. you may find that they don't work reliably. This is because you need to use a transform to get the mouse position relative to the current screen, not the entire viewing area which consists of all your monitors. Something like this...(where "this" is a WPF window).
var transform = PresentationSource.FromVisual(this).CompositionTarget.TransformFromDevice;
var mouse = transform.Transform(GetMousePosition());
public System.Windows.Point GetMousePosition()
{
var point = Forms.Control.MousePosition;
return new Point(point.X, point.Y);
}
This works without having to use forms or import any DLLs:
using System.Windows;
using System.Windows.Input;
/// <summary>
/// Gets the current mouse position on screen
/// </summary>
private Point GetMousePosition()
{
// Position of the mouse relative to the window
var position = Mouse.GetPosition(Window);
// Add the window position
return new Point(position.X + Window.Left, position.Y + Window.Top);
}
You may use combination of TimerDispatcher (WPF Timer analog) and Windows "Hooks" to catch cursor position from operational system.
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetCursorPos(out POINT pPoint);
Point is a light struct. It contains only X, Y fields.
public MainWindow()
{
InitializeComponent();
DispatcherTimer dt = new System.Windows.Threading.DispatcherTimer();
dt.Tick += new EventHandler(timer_tick);
dt.Interval = new TimeSpan(0,0,0,0, 50);
dt.Start();
}
private void timer_tick(object sender, EventArgs e)
{
POINT pnt;
GetCursorPos(out pnt);
current_x_box.Text = (pnt.X).ToString();
current_y_box.Text = (pnt.Y).ToString();
}
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
this.X = x;
this.Y = y;
}
}
This solution is also resolving the problem with too often or too infrequent parameter reading so you can adjust it by yourself. But remember about WPF method overload with one arg which is representing ticks not milliseconds.
TimeSpan(50); //ticks
If you're looking for a 1 liner, this does well.
new Point(Mouse.GetPosition(mWindow).X + mWindow.Left, Mouse.GetPosition(mWindow).Y + mWindow.Top)
The + mWindow.Left and + mWindow.Top makes sure the position is in the right place even when the user drags the window around.
Mouse.GetPosition(mWindow) gives you the mouse position relative to the parameter of your choice.
mWindow.PointToScreen() convert the position to a point relative to the screen.
So mWindow.PointToScreen(Mouse.GetPosition(mWindow)) gives you the mouse position relative to the screen, assuming that mWindow is a window(actually, any class derived from System.Windows.Media.Visual will have this function), if you are using this inside a WPF window class, this should work.
I wanna use this code
Point PointA;
private void Button_PreviewMouseUp(object sender, MouseButtonEventArgs e) {
PointA = e.MouseDevice.GetPosition(sender as UIElement);
}
private void Button_Click(object sender, RoutedEventArgs e) {
// use PointA Here
}

How to draw connecting lines between two controls on a grid WPF

I am creating controls (say button) on a grid. I want to create a connecting line between controls.
Say you you do mousedown on one button and release mouse over another button. This should draw a line between these two buttons.
Can some one help me or give me some ideas on how to do this?
Thanks in advance!
I'm doing something similar; here's a quick summary of what I did:
Drag & Drop
For handling the drag-and-drop between controls there's quite a bit of literature on the web (just search WPF drag-and-drop). The default drag-and-drop implementation is overly complex, IMO, and we ended up using some attached DPs to make it easier (similar to these). Basically, you want a drag method that looks something like this:
private void onMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
UIElement element = sender as UIElement;
if (element == null)
return;
DragDrop.DoDragDrop(element, new DataObject(this), DragDropEffects.Move);
}
On the target, set AllowDrop to true, then add an event to Drop:
private void onDrop(object sender, DragEventArgs args)
{
FrameworkElement elem = sender as FrameworkElement;
if (null == elem)
return;
IDataObject data = args.Data;
if (!data.GetDataPresent(typeof(GraphNode))
return;
GraphNode node = data.GetData(typeof(GraphNode)) as GraphNode;
if(null == node)
return;
// ----- Actually do your stuff here -----
}
Drawing the Line
Now for the tricky part! Each control exposes an AnchorPoint DependencyProperty. When the LayoutUpdated event is raised (i.e. when the control moves/resizes/etc), the control recalculates its AnchorPoint. When a connecting line is added, it binds to the DependencyProperties of both the source and destination's AnchorPoints. [EDIT: As Ray Burns pointed out in the comments the Canvas and grid just need to be in the same place; they don't need to be int the same hierarchy (though they may be)]
For updating the position DP:
private void onLayoutUpdated(object sender, EventArgs e)
{
Size size = RenderSize;
Point ofs = new Point(size.Width / 2, isInput ? 0 : size.Height);
AnchorPoint = TransformToVisual(node.canvas).Transform(ofs);
}
For creating the line class (can be done in XAML, too):
public sealed class GraphEdge : UserControl
{
public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(Point), typeof(GraphEdge), new FrameworkPropertyMetadata(default(Point)));
public Point Source { get { return (Point) this.GetValue(SourceProperty); } set { this.SetValue(SourceProperty, value); } }
public static readonly DependencyProperty DestinationProperty = DependencyProperty.Register("Destination", typeof(Point), typeof(GraphEdge), new FrameworkPropertyMetadata(default(Point)));
public Point Destination { get { return (Point) this.GetValue(DestinationProperty); } set { this.SetValue(DestinationProperty, value); } }
public GraphEdge()
{
LineSegment segment = new LineSegment(default(Point), true);
PathFigure figure = new PathFigure(default(Point), new[] { segment }, false);
PathGeometry geometry = new PathGeometry(new[] { figure });
BindingBase sourceBinding = new Binding {Source = this, Path = new PropertyPath(SourceProperty)};
BindingBase destinationBinding = new Binding { Source = this, Path = new PropertyPath(DestinationProperty) };
BindingOperations.SetBinding(figure, PathFigure.StartPointProperty, sourceBinding);
BindingOperations.SetBinding(segment, LineSegment.PointProperty, destinationBinding);
Content = new Path
{
Data = geometry,
StrokeThickness = 5,
Stroke = Brushes.White,
MinWidth = 1,
MinHeight = 1
};
}
}
If you want to get a lot fancier, you can use a MultiValueBinding on source and destination and add a converter which creates the PathGeometry. Here's an example from GraphSharp. Using this method, you could add arrows to the end of the line, use Bezier curves to make it look more natural, route the line around other controls (though this could be harder than it sounds), etc., etc.
See also
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/dd246675-bc4e-4d1f-8c04-0571ea51267b
http://www.codeproject.com/KB/WPF/WPFDiagramDesigner_Part1.aspx
http://www.codeproject.com/KB/WPF/WPFDiagramDesigner_Part2.aspx
http://www.codeproject.com/KB/WPF/WPFDiagramDesigner_Part3.aspx
http://www.codeproject.com/KB/WPF/WPFDiagramDesigner_Part4.aspx
http://www.syncfusion.com/products/user-interface-edition/wpf/diagram
http://www.mindscape.co.nz/products/wpfflowdiagrams/

Resources