本文介绍了GetCaretPos()工作不正常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用GetCaretPos()Win32 Api来获取TextBox的插入符的位置(即使它是不可见的),如果TextBox只有1行,它似乎工作正常。但它拥有的线越多,插入符号的Y坐标(从GetCaretPos()获得)就越不同。

来自GetCaretPos()的插入符号的Y坐标始终是比插入符号的实际Y坐标更好(TextBox的行数越多,就越大)。



你能给我任何解决方案吗?



这是代码:



I want to use GetCaretPos() Win32 Api to get the position of the caret of a TextBox (even when it''s invisble), it seems to work OK if the TextBox has only 1 line. But the more lines it has, the more different the Y-coordinate of the caret (which is got from GetCaretPos()) is.
The Y-coordinate of the caret getting from GetCaretPos() is always great than the actual Y-coordinate of the caret (the more lines the TextBox has, the greater it is).

Could you please give me any solution for this?

Here is the code:

[DllImport("user32")]
private extern static int GetCaretPos(out Point p);
[DllImport("user32")]
private extern static int SetCaretPos(int x, int y);
[DllImport("user32")]
private extern static bool ShowCaret(IntPtr hwnd);
[DllImport("user32")]
private extern static int CreateCaret(IntPtr hwnd, IntPtr hBitmap, int width, int height);
//Suppose I have a TextBox with a few lines already input.
//And I'll make it invisible to hide the real caret, create a new caret and set its position to see how the difference between them is.

private void TestCaret(){
   textBox1.Visible = false;//textBox1 is the only Control on the Form and has been focused.
   CreateCaret(Handle, IntPtr.Zero, 2, 20);
   Point p;
   GetCaretPos(out p);//Retrieve Location of the real caret (calculated in textBox1's coordinates)
   SetCaretPos(p.X + textBox1.Left, p.Y + textBox1.Top);
   ShowCaret(Handle);
}





正如我所说,textBox1在Form上的任何地方,当它不可见时,调用方法上面将显示真实(隐藏)插入符号的确切位置处的伪造插入符号,当textBox1只有1行时,它可以正常工作,但是......(我在上面提到过)。



我的帮助将非常感谢...谢谢!



VipHaLong



As I said, anywhere the textBox1 is on the Form, when it''s invisible, calling the method above will show a faked caret at the exact position of the real (hidden) caret, it works OK when textBox1 has only 1 line, but ... (I mentioned above).

Your help would be highly appreciated... Thanks!

VipHaLong

推荐答案


tbx.Click += new EventHandler(WhereIsTheCaret_Click);

private void WhereIsTheCaret_Click(object sender, EventArgs e) {
  Point p;
  GetCaretPos(out p);
  Debug.Print("Caret {0}, Index {1} IndexPos {2}",
    p, tbx.SelectionStart, tbx.GetPositionFromCharIndex(tbx.SelectionStart));
}





无论我在多行TextBox中点击什么,从GetCaretPos或从Selection中获得的Point的值都是同样。



艾伦。



Wherever I click in a multiline TextBox the value of the Point obtained either from GetCaretPos or from the Selection are the same.

Alan.


这篇关于GetCaretPos()工作不正常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 04:45