System windows point system drawing point

What's the difference between System.Drawing.Point and the System.Windows.Point? In what context should which one be used? I'm working with WPF.

System.Drawing.Point represents a GDI point and is used in Windows Forms. It can only hold integer values.

WPF doesn’t use GDI anymore, so it has its own System.Windows.Point type to represents a point, which can have non integer values.

answered Apr 17, 2010 at 19:07

Thomas Levesque's user avatar

Thomas LevesqueThomas Levesque

284k66 gold badges616 silver badges750 bronze badges

3

One is used with the classes in System.Drawing namespaces, and one is used with WPF.

The System.Drawing.Point is not so surprisingly used with the classes in the System.Drawing namespaces. The System.Windows.Point is used with WPF.

answered Apr 17, 2010 at 18:50

Guffa's user avatar

GuffaGuffa

679k108 gold badges728 silver badges999 bronze badges

1

  • Remove From My Forums
  • Question

  • I have been fighting this for a while, I am making a WPF DVD playback control and it works great and can even take you to the root menu, title menu, and everything. However I am trying to get it to detect my mouse when it is over an option on the DVD however I need a System.Drawing.Point and WPF uses a System.Windows.Point. So I need to be able to convert System.windows.Point to System.Drawing.Point. Windows.Point is a double and Drawing.Point is a int.

    Thank you sooooooooo much ahead!
    Brandon

Answers

  • So just instantiate one. You can either truncate or round the double values when converting them to ints.

    Point p = new Point(Convert.ToInt32(wpfPoint.X), Convert.ToInt32(wpfPoint.Y));


    Controls for WPF and Windows Forms at http://www.divelements.co.uk

    • Marked as answer by

      Tuesday, December 16, 2008 7:29 AM

Во-первых, я пока не нашел ответа. Статья здесь, на этом сайте, не отвечает на мой вопрос: Конвертер System.Drawing.Point ‘to’ System.Windows.Point

В приведенной выше статье предлагается сделать так:

    //convert
System.Drawing.Point dp = …;
return new System.Windows.Point(dp.X, dp.Y);

Но преобразование, похоже, не дает правильного результата. Я получил System.Drawing.Point из события щелчка WinForm, который встраивает визуализацию WPF. Когда я пытаюсь идентифицировать элемент управления, щелкнутый в визуализации WPF, используя вышеуказанное преобразование, и VisualTreeHelper.HitTest(), верхний левый элемент управления может быть идентифицирован правильно, тем более правдоподовым является более неточным. Это означает, что преобразование точки не является простой копией X-to-X и Y-to-Y. Должны быть и другие факторы. Любые идеи, нужно ли нам учитывать другие факторы отображения при конверсии? Запустите прилагаемую программу и нажмите на другую точку на Grid, вы узнаете странное поведение.

Задний план:

У меня есть интерфейс WPF, встроенный в WinForm. Когда HelpButton “?” на WinForm, а затем щелчок на элементе управления в пользовательском интерфейсе WPF, WinForm получит уведомление, и я могу получить правильный System.Drawing.Point в WinForm. Затем я хочу получить соответствующее местоположение, щелкнув в WPF. Я вычислил относительный System.Drawing.Point для ElementHost, который является последним элементом WinForm, связанным с первым визуальным WPF, затем попытайтесь использовать вышеописанный способ получить System.Windows.Point внутри интерфейса WPF, но он не получает правильной точки, что соответствует выбранному местоположению.

Дополнительные сведения:

У нас есть сторонние библиотеки пользовательского интерфейса, такие как UserControls, которые нельзя изменить. Мы используем WinForm для их хранения. Однако мы хотим вмешаться в UserControls и добавить Help-Window, когда пользователь нажимает “?” на WinForm (тогда курсор мыши изменится на?), а затем щелкните элемент управления пользовательского интерфейса в UserControls. Это отлично работает, если сторонний пользовательский интерфейс написан исключительно в WinForm.

Мы сделали то, что сначала мы получили точку щелчка внутри WinForm: System.Drawing.Point pt = this.PointToClient(e.MousePos);

затем получил самый передний контроль. Form.GetChildAtPoint (пт);

Затем полученный путь визуального дерева к этому элементу управления рекурсивно взбирался на визуальное дерево и записывал свойство Name или Text для каждого элемента управления в пути: Control parent = child.Parent;

Затем мы используем путь в виде строки для поиска предопределенной таблицы для определения ключевого слова, чтобы идентифицировать этот элемент управления. Как только элемент управления идентифицируется ключевым словом, ключевое слово может отображаться в окне справки или в его подсказке.

Вышеупомянутая процедура работает отлично, если все это WinForm.

Однако, когда UserControl содержит ElementHost и встроенный контент WPF, вышесказанное нарушено. Я думаю, что до тех пор, пока я правильно переведу “System.Drawing.Point” в “System.Windows.Point”, он также должен работать.

Следующий код демонстрирует проблему: Процедура репродуцирования:

  1. Запустите программу.

  2. Нажмите на “?” , курсор изменится на “?”.

  3. Нажмите на одну из 3 кнопок, всплывающее окно даст визуальный путь.

  4. Для двух кнопок в гриде первый дает путь WPF, а второй – нет, потому что System.Windows.Point неверен.

    //Please add into project the reference to (right click the project and select "Add Reference"):
    //WindowsBase
    //WindowsFormsIntegration
    //PresentationCore
    //PresentationFramework
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Forms.Integration;
    using System.Windows.Media;
    namespace WindowsFormsApplication1
    {
    

    public partial class Form1: Form {[DllImport (“user32.dll”)] static extern IntPtr GetFocus();

      public Form1()
    {
    
    InitializeComponent();
    
    System.Windows.Controls.Button b = new System.Windows.Controls.Button();
    b.Content = "WPF_Button";
    b.Name = "WPF_Button_name";
    Grid.SetColumn(b, 0);
    Grid.SetRow(b, 0);
    
    System.Windows.Controls.Button b2 = new System.Windows.Controls.Button();
    b2.Content = "WPF_Button2";
    b2.Name = "WPF_Button_name2";
    Grid.SetColumn(b2, 2);
    Grid.SetRow(b2, 2);
    
    Grid g = new Grid();
    g.Name = "WPF_Grid";
    g.Width = 250;
    g.Height = 100;
    g.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
    g.VerticalAlignment = VerticalAlignment.Stretch;
    g.ShowGridLines = true;
    
    // Define the Columns
    ColumnDefinition colDef1 = new ColumnDefinition();
    ColumnDefinition colDef2 = new ColumnDefinition();
    ColumnDefinition colDef3 = new ColumnDefinition();
    g.ColumnDefinitions.Add(colDef1);
    g.ColumnDefinitions.Add(colDef2);
    g.ColumnDefinitions.Add(colDef3);
    
    // Define the Rows
    RowDefinition rowDef1 = new RowDefinition();
    RowDefinition rowDef2 = new RowDefinition();
    RowDefinition rowDef3 = new RowDefinition();
    RowDefinition rowDef4 = new RowDefinition();
    g.RowDefinitions.Add(rowDef1);
    g.RowDefinitions.Add(rowDef2);
    g.RowDefinitions.Add(rowDef3);
    g.RowDefinitions.Add(rowDef4);
    
    
    g.Children.Add(b);
    g.Children.Add(b2);
    
    this.elementHost1.Child = g;
    
    }
    
    // More usefull version of GetChildAtPoint
    public static System.Windows.Forms.Control FindChildAtPoint(System.Windows.Forms.Control parent, System.Drawing.Point pt, ref string path, out System.Drawing.Point relative_point_inside_child)
    {
    //Find a child
    System.Windows.Forms.Control child = parent.GetChildAtPoint(pt);
    //If no child, this is the control at the mouse cursor
    if (child == null)
    {
    path += parent.Name;
    //Offset our current position to be relative to the child to get the point inside the child.
    relative_point_inside_child = new System.Drawing.Point(pt.X, pt.Y);
    return parent;
    }
    path += parent.Name + "\";
    //If a child, offset our current position to be relative to the child
    System.Drawing.Point childPoint = new System.Drawing.Point(pt.X - child.Location.X, pt.Y - child.Location.Y);
    //Find child of child control at offset position
    return FindChildAtPoint(child, childPoint, ref path, out relative_point_inside_child);
    }
    
    
    private void Form1_HelpRequested(object sender, HelpEventArgs e)
    {
    if (System.Windows.Forms.Control.MouseButtons == MouseButtons.None)
    {
    //No mouse activity, this function is entered because of F1 key press.
    //Get the focused Control. If no focused Control then launch overall Help-Window.
    //
    IntPtr handle = GetFocus();
    if (handle != IntPtr.Zero)
    {
    System.Windows.Forms.Control ctl = System.Windows.Forms.Control.FromHandle(handle);
    //Got the ctl, do whatever
    }
    }
    else
    { // Help Button ? pressed (After click ?, the mouse cursor changes to ?,
    // Then user can move the mouse to a UI Control and click it, in this case,
    // we need find the control that is clicked, the control might not be focused
    // in such case.
    // Convert screen coordinates to client coordinates
    System.Drawing.Point p = this.PointToClient(e.MousePos);
    System.Drawing.Point pt = this.PointToClient(Cursor.Position);
    
    //Look for control user clicked on
    System.Drawing.Point relative_point_inside_child;
    string path = "";
    System.Windows.Forms.Control ctl = FindChildAtPoint(this, pt, ref path, out relative_point_inside_child);
    
    if (ctl is ElementHost)
    {
    // This is a WPF view embedded in WinForm, get the root Control
    UIElement wpf_root = (ctl as ElementHost).Child;
    if (wpf_root != null)
    {
    System.Windows.Point pt_WPF = new System.Windows.Point(relative_point_inside_child.X, relative_point_inside_child.Y);
    HitTestResult htr = VisualTreeHelper.HitTest(wpf_root, pt_WPF);
    if (htr != null && htr.VisualHit != null)
    {
    //IInputElement elem = System.Windows.Input.Mouse.DirectlyOver;
    string pathWPF = "";
    if (htr.VisualHit is DependencyObject)
    {
    FindPathOfControlWPF(htr.VisualHit, ref pathWPF);
    }
    if (pathWPF != "")
    {
    path = path + pathWPF;
    }
    }
    }
    }
    System.Windows.Forms.MessageBox.Show("Clicked on PATH: " + path);
    e.Handled = true;
    }
    
    }
    
    
    //WPF version of More usefull version of FindPathOfControl
    public static System.Windows.DependencyObject FindPathOfControlWPF(System.Windows.DependencyObject child, ref string path)
    {
    //Find a parent
    System.Windows.DependencyObject parent
    = System.Windows.Media.VisualTreeHelper.GetParent(child);
    
    if (child is System.Windows.Controls.TextBlock)
    {
    path = ":" + (child as System.Windows.Controls.TextBlock).Text + path;
    }
    else if (child is System.Windows.Controls.Label)
    {
    path = ":" + (child as System.Windows.Controls.Label).Content.ToString() + path;
    }
    else if (child is System.Windows.Controls.Primitives.ButtonBase)
    {
    path = ":" + (child as System.Windows.Controls.Primitives.ButtonBase).Content.ToString() + path;
    }
    
    if (child is System.Windows.FrameworkElement)
    {
    path = (child as System.Windows.FrameworkElement).Name + path;
    }
    
    //If no parent, this is the top control
    if (parent == null)
    {
    return child;
    }
    path = "\" + path;
    //Find parent of child control
    return FindPathOfControlWPF(parent, ref path);
    }
    
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;
    
    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
    if (disposing && (components != null))
    {
    components.Dispose();
    }
    base.Dispose(disposing);
    }
    
    #region Windows Form Designer generated code
    
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
    //this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
    //this.flowLayoutPanel1 = new System.Windows.Forms.Panel();
    this.panel1 = new System.Windows.Forms.Panel();
    this.button1 = new System.Windows.Forms.Button();
    this.panel2 = new System.Windows.Forms.Panel();
    this.elementHost1 = new System.Windows.Forms.Integration.ElementHost();
    //this.flowLayoutPanel1.SuspendLayout();
    this.panel1.SuspendLayout();
    this.panel2.SuspendLayout();
    this.SuspendLayout();
    //
    // flowLayoutPanel1
    //
    //this.flowLayoutPanel1.Controls.Add(this.panel1);
    //this.flowLayoutPanel1.Controls.Add(this.panel2);
    //this.flowLayoutPanel1.Location = new System.Drawing.Point(24, 33);
    //this.flowLayoutPanel1.Name = "flowLayoutPanel1";
    //this.flowLayoutPanel1.Size = new System.Drawing.Size(242, 205);
    //this.flowLayoutPanel1.TabIndex = 0;
    //this.flowLayoutPanel1.BackColor = System.Drawing.Color.Blue;
    //
    // panel1
    //
    this.panel1.Controls.Add(this.button1);
    this.panel1.Location = new System.Drawing.Point(3, 3);
    this.panel1.Name = "panel1";
    this.panel1.Size = new System.Drawing.Size(90, 134);
    this.panel1.TabIndex = 0;
    this.panel1.BackColor = System.Drawing.Color.Green;
    this.panel1.BringToFront();
    //
    // button1
    //
    this.button1.Location = new System.Drawing.Point(16, 39);
    this.button1.Name = "button1";
    this.button1.Size = new System.Drawing.Size(60, 35);
    this.button1.TabIndex = 0;
    this.button1.Text = "button1";
    this.button1.UseVisualStyleBackColor = true;
    this.button1.BackColor = System.Drawing.Color.Yellow;
    this.panel1.BringToFront();
    //
    // panel2
    //
    this.panel2.Controls.Add(this.elementHost1);
    this.panel2.Location = new System.Drawing.Point(99, 3);
    this.panel2.Name = "panel2";
    this.panel2.Size = new System.Drawing.Size(300, 300);
    this.panel2.TabIndex = 1;
    this.panel2.BackColor = System.Drawing.Color.Purple;
    this.panel1.BringToFront();
    //
    // elementHost1
    //
    this.elementHost1.Dock = System.Windows.Forms.DockStyle.Fill;
    this.elementHost1.Location = new System.Drawing.Point(0, 0);
    this.elementHost1.Name = "elementHost1";
    this.elementHost1.TabIndex = 0;
    this.elementHost1.Text = "elementHost1Text";
    this.elementHost1.Child = null;
    this.panel1.BringToFront();
    //
    // Form1
    //
    this.HelpButton = true;
    this.MaximizeBox = false;
    this.MinimizeBox = false;
    this.HelpRequested += new System.Windows.Forms.HelpEventHandler(this.Form1_HelpRequested);
    this.Size = new System.Drawing.Size(600, 600);
    this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
    this.ClientSize = new System.Drawing.Size(600, 600);
    //this.Controls.Add(this.flowLayoutPanel1);
    this.Controls.Add(this.panel1);
    this.Controls.Add(this.panel2);
    this.Name = "Form1";
    this.Text = "Form1";
    this.BackColor = System.Drawing.Color.Red;
    //this.flowLayoutPanel1.ResumeLayout(false);
    this.panel1.ResumeLayout(false);
    this.panel2.ResumeLayout(false);
    this.ResumeLayout(false);
    
    }
    
    #endregion
    //private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
    //private System.Windows.Forms.Panel flowLayoutPanel1;
    private System.Windows.Forms.Panel panel1;
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.Panel panel2;
    private System.Windows.Forms.Integration.ElementHost elementHost1;
    

    }}

Наконец, я нашел решение (прочитав больше о координатах экрана WPF и других тестах).

Основная причина заключается в том, что “новый System.Windows.Point(dp.X, dp.Y)” не будет надежно работать на разных разрешениях, компьютерах с несколькими мониторами и т.д. Ему нужно было использовать преобразование для получения положения мыши относительно текущего экрана, а не всей области просмотра, которая состоит из всех мониторов.

Ответ на другой вопрос помог мне: как получить текущие координаты экрана мыши в WPF?

Если изменить следующие две строки моего кода:

          System.Windows.Point pt_WPF = new System.Windows.Point(relative_point_inside_child.X, relative_point_inside_child.Y);
          HitTestResult htr = VisualTreeHelper.HitTest(wpf_root, pt_WPF);

К следующему:

          System.Windows.Point pt_WPF = new System.Windows.Point(relative_point_inside_child.X, relative_point_inside_child.Y);
           var transform = PresentationSource.FromVisual(wpf_root).CompositionTarget.TransformFromDevice;
          pt_WPF = transform.Transform(pt_WPF);
          HitTestResult htr = VisualTreeHelper.HitTest(wpf_root, pt_WPF);

Тогда он отлично работает.

This C# tutorial demonstrates the Point type, which is found in System.Drawing.

Point represents an X and a Y coordinate grouped together.

Points are useful whenever you need to store coordinates. Sometimes other methods in the .NET Framework require this type.

Point. An empty Point is one where X and Y are equal to zero. You can use the constructor that receives two integers to create a Point. Next, we show Point.Add and Subtract: these add or subtract each coordinate from a Point and a Size.

Finally: Point.Ceiling, Round and Truncate all act upon a PointF argument. They compute a mathematical function on each coordinate.

Math.CeilingMath.RoundMath.Truncate

C# program that uses Point

using System;
using System.Drawing;

class Program
{
    static void Main()
    {
	// Empty point.
	Point point0 = new Point();
	Console.WriteLine(point0);
	Console.WriteLine(point0.IsEmpty);

	// Create point.
	Point point1 = new Point(4, 6);
	Console.WriteLine(point1); // 4, 6

	// Create size.
	Size size = new Size(2, 2);

	// Add point and size.
	Point point3 = Point.Add(point1, size);
	Console.WriteLine(point3); // 6, 8

	// Subtract size from point.
	Point point4 = Point.Subtract(point1, size);
	Console.WriteLine(point4); // 2, 4

	// Compute ceiling from PointF.
	Point point5 = Point.Ceiling(new PointF(4.5f, 5.6f));
	Console.WriteLine(point5); // 5, 6

	// Round to point.
	Point point6 = Point.Round(new PointF(4.5f, 5.7f));
	Console.WriteLine(point6); // 4, 6

	// Truncate to point.
	Point point7 = Point.Truncate(new PointF(4.7f, 5.8f));
	Console.WriteLine(point7); // 4, 5
    }
}

Output

{X=0,Y=0}
True
{X=4,Y=6}
{X=6,Y=8}
{X=2,Y=4}
{X=5,Y=6}
{X=4,Y=6}
{X=4,Y=5}

PointF. The PointF type is the same as the Point type but it stores floating point numbers (float). The decision of which to use depends on the nature of the coordinate system in your program.

Tip: You can create a PointF instance in two ways. One way uses two floating-point arguments. The other uses the parameterless constructor.

C# program that uses PointF struct

using System;
using System.Drawing;

class Program
{
    static void Main()
    {
	PointF pointF = new PointF(4.5f, 6.5f);
	Display(pointF);

	pointF = new PointF();
	Display(pointF);

	pointF = new PointF(0, 0);
	Display(pointF);
    }

    static void Display(PointF pointF)
    {
	Console.WriteLine(pointF);
	Console.WriteLine(pointF.X);
	Console.WriteLine(pointF.Y);
	Console.WriteLine(pointF.IsEmpty);
    }
}

Output

{X=4.5, Y=6.5}
4.5
6.5
False
{X=0, Y=0}
0
0
True
{X=0, Y=0}
0
0
True

Emptiness. Conceptually, any PointF that has 0 as its X property and 0 as its Y property is empty. You can see that the default PointF is empty, and a PointF created with arguments 0, 0 is also empty.

Point versus PointF. What is the difference between Point and PointF? Point uses integer coordinates (specified by the int type). PointF uses floating-point (float) coordinates—these have a fractional part.

Class or struct: Is the PointF type a class or a struct? We find that PointF is a struct type.

Note: The documentation for the PointF constructor with two arguments calls it a class. In most programs, this makes no difference.

The PointF type provides a way for you to represent a coordinate of floating-point values. This can be used in various types in the System.Drawing namespace or in any other code that requires this representation in memory.

SizeF

Summary. We looked the Point type from the System.Drawing namespace in the .NET Framework. Another option you could use instead of Point is a KeyValuePair of two integers, but this would not provide the helper methods available on Point.

However: The KeyValuePair would eliminate the need to include the System.Drawing namespace.

KeyValuePair


Related Links

Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf

2 ответы

System.Drawing.Point представляет точку GDI и используется в Windows Forms. Он может содержать только целые значения.

WPF больше не использует GDI, поэтому у него есть собственный System.Windows.Point type для представления точки, которая может иметь нецелочисленные значения.

ответ дан 17 апр.

Один используется с классами в пространствах имен System.Drawing, а другой — с WPF.

Неудивительно, что System.Drawing.Point используется с классами в пространствах имен System.Drawing. System.Windows.Point используется с WPF.

ответ дан 17 апр.

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

wpf
2d

or задайте свой вопрос.

        /// <summary>
        /// Changes the cursor for this control to show the coordinates
        /// </summary>
        /// <param name="uiElement"></param>
        private void SetCoordinatesOnCursor(FrameworkElement uiElement)
        {
            Point coordinate = locked ? lockPoint : lastCoordinate;
            Cursor newCursor = null;
            var cursorFont = new Font("Arial", 8f);

            try
            {
                // Lets get the string to be printed
                string coordinateText = coordinate.X.ToString(xFormat) + "," + coordinate.Y.ToString(yFormat);
                // Calculate the rectangle required to draw the string
                SizeF textSize = GetTextSize(coordinateText, cursorFont);

                // ok, so here's the minimum 1/4 size of the bitmap we need, as the
                // Hotspot for the cursor will be in the centre of the bitmap.
                int minWidth = 8 + (int) Math.Ceiling(textSize.Width);
                int minHeight = 8 + (int) Math.Ceiling(textSize.Height);

                // If the bitmap needs to be resized, then resize it, else just clear it
                if (cursorBitmap.Width < minWidth*2 || cursorBitmap.Height < minHeight*2)
                {
                    Bitmap oldBitmap = cursorBitmap;
                    cursorBitmap = new Bitmap(Math.Max(cursorBitmap.Width, minWidth*2),
                                              Math.Max(cursorBitmap.Height, minHeight*2));
                    oldBitmap.Dispose();
                }

                // Get the centre of the bitmap which will be the Hotspot
                var centre = new System.Drawing.Point(cursorBitmap.Width/2, cursorBitmap.Height/2);
                /// Calculate the text rectangle
                var textRectangle = new Rectangle(centre.X + 8, centre.Y + 8, minWidth - 8, minHeight - 8);

                int diff = (int) cursorPosition.X + textRectangle.Right/2 - 3 - (int) uiElement.ActualWidth;

                if (diff > 0)
                {
                    textRectangle.Location = new System.Drawing.Point(textRectangle.Left - diff, textRectangle.Top);
                }

                // Draw the target symbol, and the coordinate text on the bitmap
                using (Graphics g = Graphics.FromImage(cursorBitmap))
                {
                    g.SmoothingMode = SmoothingMode.AntiAlias;
                    // This line causes a crash on laptops when you render a string
                    // g.CompositingMode = CompositingMode.SourceCopy;
                    g.Clear(Color.Transparent);

                    float targetX = centre.X;
                    float targetY = centre.Y;

                    float radius = 30;

                    if (!locked)
                    {
                        var blackPen = new Pen(Color.FromArgb(255, 0, 0, 0), 1.4f);
                        g.DrawEllipse(blackPen, targetX - radius*.5f, targetY - radius*.5f, radius, radius);
                        g.DrawLine(blackPen, targetX - radius*.8f, targetY, targetX - 2f, targetY);
                        g.DrawLine(blackPen, targetX + 2f, targetY, targetX + radius*.8f, targetY);
                        g.DrawLine(blackPen, targetX, targetY - radius*.8f, targetX, targetY - 2f);
                        g.DrawLine(blackPen, targetX, targetY + 2f, targetX, targetY + radius*.8f);
                    }
                    else
                    {
                        var blackPen = new Pen(Color.FromArgb(255, 0, 0, 0), 3f);
                        var yellowPen = new Pen(Color.FromArgb(255, 255, 255, 0), 2f);
                        g.DrawEllipse(blackPen, targetX - radius*.5f, targetY - radius*.5f, radius, radius);
                        g.DrawEllipse(yellowPen, targetX - radius*.5f, targetY - radius*.5f, radius, radius);
                    }

                    if (!locked)
                        g.FillRectangle(new SolidBrush(Color.FromArgb(127, 255, 255, 255)), textRectangle);
                    else
                        g.FillRectangle(new SolidBrush(Color.FromArgb(170, 255, 255, 0)), textRectangle);

                    // Setup the text format for drawing the subnotes
                    using (var stringFormat = new StringFormat())
                    {
                        stringFormat.Trimming = StringTrimming.None;
                        stringFormat.FormatFlags = StringFormatFlags.NoClip | StringFormatFlags.NoWrap;
                        stringFormat.Alignment = StringAlignment.Near;

                        // Draw the string left aligned
                        g.DrawString(
                            coordinateText,
                            cursorFont,
                            new SolidBrush(Color.Black),
                            textRectangle,
                            stringFormat);
                    }
                }

                // Now copy the bitmap to the cursor
                newCursor = WPFCursorFromBitmap.CreateCursor(cursorBitmap);
            }
            catch
            {
                Trace.WriteLine("Error drawing on cursor");
            }
            finally
            {
                // After the new cursor has been set, the unmanaged resources can be
                // cleaned up that were being used by the old cursor
                if (newCursor != null)
                {
                    uiElement.Cursor = newCursor;
                }
                if (lastCursor != null)
                {
                    lastCursor.Dispose();
                }
                lastCursor = newCursor;

                // Save the new values for cleaning up on the next pass
            }
        }

Понравилась статья? Поделить с друзьями:
  • System windows markup xamlparseexception не обнаружено подходящего конструктора для типа
  • System service exception windows 10 причина ntfs sys
  • System windows markup xamlparseexception задание значения connectionid вызвало исключение
  • System windows forms screen primaryscreen bounds
  • System windows forms messagebox system windows forms messagebox