简体   繁体   中英

Painting a TextBox

I'm in need of a way to make TextBox appear like a parallelogram but i can't figure out how to do so. I currently have this code:

private void IOBox_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;
    Point cursor = PointToClient(Cursor.Position);
    Point[] points = { cursor, new Point(cursor.X + 50, cursor.Y), new Point(cursor.X + 30, cursor.Y - 20),
                         new Point(cursor.X - 20, cursor.Y - 20) };
    Pen pen = new Pen(SystemColors.MenuHighlight, 2);
    g.DrawLines(pen, points);
}

But apparently it's not working. Either i misplaced/misused it or i'm not doing something right. This is the method that i use to add it.

int IOCounter = 0;
private void inputOutput_Click(object sender, EventArgs e)
{
    IOBox box = new IOBox();
    box.Name = "IOBox" + IOCounter;
    IOCounter++;
    box.Location = PointToClient(Cursor.Position);
    this.Controls.Add(box);
}

Any idea how i can fix it? IOBox is a UserControl made by me which contains a TextBox. Is that rightful to do?

If its possible, you should make your application using WPF. WPF is designed to do exactly what you are trying to do.

However, it can be done in WinForms, though not easily. You will need to make a new class that inherits the TextBox WinForm control. Here is an example that makes a TextBox look like a circle:

public class MyTextBox : TextBox
{
    public MyTextBox() : base()
    {
        SetStyle(ControlStyles.UserPaint, true);
        Multiline = true;
        Width = 130;
        Height = 119;
    }

    public override sealed bool Multiline
    {
        get { return base.Multiline; }
        set { base.Multiline = value; }
    }

    protected override void OnPaintBackground(PaintEventArgs e)
    {
        var buttonPath = new System.Drawing.Drawing2D.GraphicsPath();
        var newRectangle = ClientRectangle;

        newRectangle.Inflate(-10, -10);
        e.Graphics.DrawEllipse(System.Drawing.Pens.Black, newRectangle);
        newRectangle.Inflate(1, 1);
        buttonPath.AddEllipse(newRectangle);
        Region = new System.Drawing.Region(buttonPath);

        base.OnPaintBackground(e);
    }      
}

Keep in mind that you will still have to do other things, such as clipping the text, etc. But this should get you started.

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