我有一些
TextBox
,MultiLine TextBox
,RichTextBox
在我的 WindowsFormApps
中,使用 Visual Studio 2015。现在我想让我的用户在这些字段中输入文本,并且我想连续知道 Caret Pointer
的位置(X轴,Y轴),无论我的用户是在文本的末尾、开头还是文本的中间任何地方输入文本。
我能否在某些类级变量中持续获取正确的运行时位置(X轴,Y轴),以便在其他地方使用...???
添加的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DEMO_Apps
{
public partial class MainForm : Form
{
int xpos;
int ypos;
public MainForm()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
var o = Utility.GetCaretPoint(textBox1);
xpos = o.X;
ypos = o.Y;
textBox2.Text = Convert.ToString(xpos + "," + ypos);
}
}
public static class Utility
{
///for System.Windows.Forms.TextBox
public static System.Drawing.Point GetCaretPoint(System.Windows.Forms.TextBox textBox)
{
return textBox.GetPositionFromCharIndex(textBox.SelectionStart);
}
///for System.Windows.Controls.TextBox
public static System.Windows.Point GetCaretPoint(System.Windows.Controls.TextBox textBox)
{
return textBox.GetRectFromCharacterIndex(textBox.SelectionStart).Location;
}
}
}
Point locationOnForm = textBox1.FindForm().PointToClient(textBox1.Parent.PointToScreen(textBox1.Location));
,那么我们就可以获取相对于父窗体的textBox1
位置,然后可以将其与您的代码相加以获取相对于窗体的CARET轴。 :) - Muhammad Hassan