S
Steve Richter
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);
}
}
}
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);
}
}
}