SetCaretPos within OnPaint method of user control

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

Steve Richter

I doubt the issue has anything to do with the ClipRectangle.


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).

this helps a lot. thanks.

-Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top