简体   繁体   中英

My Own Editor User control in C#

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_width;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM