How do I SetCaretPos within the OnPaint method of a user control?
The caret either does not display or is not positioned where I expect
it to be. I am guessing SetCaretPos is working outside the confines
and relative location of the ClipRectangle.
in the code that follows, the caret ends up hugging the far left
border of the Form, nowhere near where the user control is located.
thanks,
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace demo_FormControl2
{
public partial class UserControl1 : UserControl
{
[DllImport("user32.dll")]
public static extern bool ShowCaret(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool SetCaretPos(int x, int y);
public UserControl1()
{
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Rectangle r2 = e.ClipRectangle;
TextRenderer.DrawText(
e.Graphics, this.Text, this.Font, this.ClientRectangle,
this.ForeColor);
Rectangle r1 = new Rectangle(
this.ClientRectangle.Left,
this.ClientRectangle.Top + 20,
this.ClientRectangle.Width,
this.ClientRectangle.Height);
TextRenderer.DrawText(
e.Graphics, "2nd line", this.Font, r1, this.ForeColor);
SetCaretPos(r1.Left, r1.Top);
ShowCaret(this.FindForm().Handle);
}
}
}
Peter Duniho - 31 Mar 2008 19:03 GMT
> How do I SetCaretPos within the OnPaint method of a user control?
>
> The caret either does not display or is not positioned where I expect
> it to be. I am guessing SetCaretPos is working outside the confines
> and relative location of the ClipRectangle.
I doubt the issue has anything to do with the ClipRectangle.
> in the code that follows, the caret ends up hugging the far left
> border of the Form, nowhere near where the user control is located.
Have you tried passing the control's own window handle to the ShowCaret()
function?
For what it's worth, the OnPaint() method isn't really a great place to be
relocating and showing the caret anyway. The only thing you should be
doing in there is actual drawing. I don't think that's related to your
problem, but I think you'll be better off in the long run setting and
showing the caret in a more appropriate place (like in the OnEnter()
override for showing it, and there and wherever else user interaction
would move the caret for setting the position).
Pete
Steve Richter - 31 Mar 2008 20:16 GMT
On Mar 31, 2:03 pm, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:
> On Mon, 31 Mar 2008 10:15:32 -0700, Steve Richter
>
[quoted text clipped - 20 lines]
> override for showing it, and there and wherever else user interaction
> would move the caret for setting the position).
this helps a lot. thanks.
-Steve