I have some TextBox
, MultiLine TextBox
, RichTextBox
in my WindowsFormApps
using Visual Studio 2015. Now I want to let my user type text in these fields and along with I want to know the Caret Pointer
position (X-Axis,Y-Axis) continuously whether my user type text in the end of text or in start of the text or any where in the middle of the text.
Can I get the correct position (X-Axis,Y-Axis) at Run Time continuously in some class level variables to use it on other places...???
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;
}
}
}
Based on your edited question, I checked the code and found that when caret is at last character, the function gives empty position so I changed a bit, the following Functions should give you what you want:
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)
{
int start = textBox.SelectionStart;
if (start == textBox.TextLength)
start --;
return textBox.GetPositionFromCharIndex(start);
}
///for System.Windows.Controls.TextBox requires reference to the following dlls: PresentationFramework, PresentationCore & WindowBase.
//So if not using those dlls you should comment the code below:
public static System.Windows.Point GetCaretPoint(System.Windows.Controls.TextBox textBox)
{
return textBox.GetRectFromCharacterIndex(textBox.SelectionStart).Location;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With