winform中如何获得TextBox光标位置_光标离开文本框事件

2020-02-29 其他范文 下载本文

winform中如何获得TextBox光标位置由刀豆文库小编整理,希望给你工作、学习、生活带来方便,猜你可能喜欢“光标离开文本框事件”。

winform中如何获得TextBox光标位置

winform中如何获得TextBox光标位置?第一反应是SelectionStart属性,结果发现在分方向选择内容时返回错误值,真正答案如下:

using System;using System.ComponentModel;using System.Windows.Forms;using System.Runtime.InteropServices;using System.Drawing;namespace WindowsApplication5...{

public partial cla Form1 : Form

...{

public Form1()

...{

InitializeComponent();

}

[DllImport(“user32.dll”)]

private static extern bool GetCaretPos(out Point ppt);

private void Form1_Load(object sender, EventArgs e)

...{

this.textBox1.Text = “jinjazz”;

}

private void Form1_MouseDown(object sender, MouseEventArgs e)

...{

Point p;

GetCaretPos(out p);

int i=this.textBox1.GetCharIndexFromPosition(p);

this.Text = i.ToString();

}

} } 在zswang(偶最pf的伴水)的提醒下,上面方法存在两个遗漏,zswang的补充如下:

1、当输入焦点没有在编辑框中(比如有多个输入框),这样光标的位置获取并非指定。

当然可以考虑获取之前先Focus()一下。

2、GetCharIndexFromPosition()方法有缺陷,当光标在最后一个字符来回的时候数值不变-_-!!得完善一下。

public virtual int GetCharIndexFromPosition(Point pt)...{

int lParam = NativeMethods.Util.MAKELONG(pt.X, pt.Y);

int n =(int)UnsafeNativeMethods.SendMeage(new HandleRef(this, base.Handle), 0xd7, 0, lParam);//EM_CHARFROMPOS = 0xd7

n = NativeMethods.Util.LOWORD(n);

if(n

...{

return 0;

}

string text = this.Text;

if(n >= text.Length)

...{

n = Math.Max(text.Length-1, 0);//

}

return n;}

《winform中如何获得TextBox光标位置.docx》
将本文的Word文档下载,方便收藏和打印
推荐度:
winform中如何获得TextBox光标位置
点击下载文档
相关专题 光标离开文本框事件 光标 如何获得 位置 光标离开文本框事件 光标 如何获得 位置
[其他范文]相关推荐
    [其他范文]热门文章
      下载全文