Files
MetroGauges-Old/MetroGauges/Controls/DrawTools/TextTool.cs
2026-02-23 17:02:55 +08:00

120 lines
3.6 KiB
C#

using MetroGauges.Controls.DrawTools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace MetroGauges.Controls
{
public class TextTool : DrawToolBase
{
TextBox textBox;
System.Timers.Timer timer = new System.Timers.Timer();
public TextTool(DesignControl canvas) : base(canvas)
{
IsStartDraw = true;
}
public override void MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (IsStartDraw)
{
Point mousePosition = Mouse.GetPosition(this.DrawDesign.canvasDesign);
if (!this.DrawDesign.canvasDesign.Children.Contains(textBox))
{
textBox = new TextBox();
textBox.Foreground= new SolidColorBrush(Colors.White);
textBox.KeyDown += TextBox_KeyDown;
this.DrawDesign.canvasDesign.Children.Add(textBox);
timer.Elapsed += Timer_Elapsed;
}
//添加文本到画布
if(!string.IsNullOrWhiteSpace(textBox.Text))
{
Point point = (Point)textBox.DataContext;
TextBlock textBlock = new TextBlock();
textBlock.Text = textBox.Text;
textBlock.Foreground = new SolidColorBrush(Colors.White);
Canvas.SetLeft(textBlock, point.X+2);
Canvas.SetTop(textBlock, point.Y+6);
textBlock.DataContext = point;
this.AddShap(textBlock);
textBox.Text = "";
}
timer.Interval = 300;
timer.Start();
Canvas.SetLeft(textBox, mousePosition.X);
Canvas.SetTop(textBox, mousePosition.Y);
textBox.DataContext = new Point() { X = mousePosition.X, Y = mousePosition.Y };
if (e == null)
{
MouseRightButtonUp(sender, e);
}
}
}
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
MouseLeftButtonDown(sender, null);
}
}
public override void Highlight(FrameworkElement shape)
{
this.DrawDesign.CrrentDrawTool = this;
base.Highlight(shape);
}
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
this.DrawDesign.Dispatcher.Invoke(new Action(() => { textBox.Focus(); }));
timer.Stop();
}
public override void MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
}
public override void MouseMove(object sender, MouseEventArgs e)
{
}
public override void MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
IsStartDraw = false;
this.DrawDesign.canvasDesign.Children.Remove(textBox);
//textBox.Focus();
}
public override void m_Root_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
}
public override void Deactivated()
{
IsStartDraw = false;
this.DrawDesign.canvasDesign.Children.Remove(textBox);
}
}
}