GetCaretPos() Win32 API を使用して、テキスト ボックスが非表示の場合でも、テキスト ボックスのキャレットの位置を取得したいと考えています。テキストボックスに 1 行しかない場合は問題ないように見えますが、行数が多いほど、キャレットの Y 座標が異なります (GetCaretPos() によって報告されます)。GetCaretPos( によって報告されるキャレットの Y 座標) は常に、キャレットの実際の Y 座標よりも大きくなります。
これは何が原因で、どうすれば修正できますか?
コードは次のとおりです。
[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
それが見えない場合、上記のメソッドを呼び出すと、実際の (隠れた) キャレットの正確な位置に偽のキャレットが表示されます。textBox1 が 1 行しかない場合は正常に機能しますが、複数行ある場合は機能しません。