使用扩展文本框取得脱字符号位置信息
环境:.Net, C#
引言
有时,我们需要知道文本框中脱字符号的位置信息。例如,在编辑器中。下面介绍一个扩展的文本框类: ExtTextBox,它增加了两个只读属性GetCaretXYPosition和GetCaretLCPosition. 其中GetCaretXYPosition返回一个Point对象,包含当前脱字符号相对于文本框的坐标信息;GetCaretLCPosition返回一个自定义的结构:CharPoint,包含了当前脱字符号在文本框中的行和列信息。
代码如下:(编译后加入到工具箱中就可以使用了)!
1using System;
2using System.Windows.Forms;
3using System.Runtime.InteropServices;
4using System.Drawing;
5using System.Collections;
6namespace TextBoxUtils
7...{
8 /**//// <summary>
9 /// 封装脱字符号在编辑框中的位置信息
10 ///L = 脱字符号所在的行
11 ///C = 脱字符号所在的列
12 /// </summary>
13 public struct CharPoint
14 ...{
15 private int l, c;
16
17 public static readonly CharPoint Empty;
18
19 static CharPoint()
20 ...{
21 CharPoint.Empty = new CharPoint();
22 }
23
24 public CharPoint(int l, int c)
25 ...{
26 this.l = l;
27 this.c = c;
28 }
29
30 public override string ToString()
31 ...{
32 return(String.Format("{{ 行 = {0}, 列 = {1}}}", this.l, this.c));
33 }
34
35 }
36
37 public class ExtTextBox : TextBox
38 ...{
39 //调用两个API函数,取得相关位置信息
40 [DllImport("user32")] private static extern IntPtr
41 SendMessage(HandleRef hWnd, int msg,int wParam, int lParam);
42 [DllImport("user32")] private static extern int
43 GetCaretPos(ref Point lpPoint);
44 private int EM_LINEINDEX = 0xbb;
45 private int EM_LINEFROMCHAR = 0xc9;
46 private int EM_GETSEL = 0xb0;
47
48
49 /**//// <summary>
50 /// 取得脱字符号相对于文本框的坐标(X, Y)信息
51 /// </summary>
52 public Point GetCaretXYPosition
53 ...{
54 get
55 ...{
56 Point pt = Point.Empty;
57 GetCaretPos(ref pt);
58 //返回坐标
59 return pt;
60 }
61 }
62
63 /**//// <summary>
64 /// 取得脱字符号所在行和列的位置信息
65 /// </summary>
66 public CharPoint GetCaretLCPosition
67 ...{
68 get
69 ...{
70 CharPoint cpt = CharPoint.Empty;
71 HandleRef hr = new HandleRef(this, base.Handle );
72 int l = (int)SendMessage(hr,EM_LINEFROMCHAR, -1, 0);
73 int sel = (int)SendMessage(hr, EM_GETSEL,0, 0);
74 int ai = sel & 0xffff;
75 int li = (int)SendMessage(hr,EM_LINEINDEX, -1, 0);
76 int c = ai - li;
77 cpt = new CharPoint(l+1,c+1);
78 return new CharPoint(l+1,c+1);
79 }
80 }
81 }
82}