开发者

My Own Editor User control in C#

开发者 https://www.devze.com 2023-02-15 03:11 出处:网络
I have a picture box, and I have used this method: CreateCaret(pictureBox1.Handle,IntPtr.Zero,1,font.Height);

I have a picture box, and I have used this method:

CreateCaret(pictureBox1.Handle,IntPtr.Zero,1,font.Height);
ShowCaret(pictureBox1.Handle);

Now I have created the caret. By following code I am going to draw on the picture-box:

gr = pictureBox1.CreateGraphics();

Now i have used this code to measure a character width:

font = new Font("Arial", 20, GraphicsUnit.Pixel);
char_width = (int)gr.MeasureString("a", font).Width;

And For Form1_keypress:

if (e.KeyChar !=(char)Keys.Enter )
{
    gr.DrawString(e.KeyChar.ToString(), font, Brushes.Black, caretpos.X, caretpos.Y);
    caretpos.X += char_wi开发者_运维问答dth;
}

But the space between characters are very big, about 26 pixels. How can I correct this?

Something like this:

A   B   C   D


Note that the dimensions passed to CreateCaret are in pixels. Presumably your font height, etc. are in points.

Also note that the caret should be created when the control gains focus and then destroyed when the control loses focus. There should be only one caret at a time so it is incorrect to maintain one when the focus goes to another window (that window might need a caret).


My first thought is it looks like your getting monospaced because of how MeasureString is working against individual characters.

Track the entire string, adding to it each keystroke and redraw / measure caret position against it as a whole rather then per char.


One thing to bear in mind is that Graphics.MeasureString() will give you a different result to TextRenderer.MeasureText()

Generally, you will want to use the TextRenderer version.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号