绘制矩形作为文本框边框

本文关键字:文本 边框 绘制 | 更新日期: 2023-09-27 18:15:37

我有这个类Validators,在那里我验证所有的文本框在我的WinForms项目。我不知道该怎么做的是:"我无法更改未验证的文本框的bordercolor"。所以我在同一个类"Validators"中使用了这个LoginForm_Paint事件。我不知道如何使用它,也许它一开始就不应该在那里,也许我不知道如何使用它。有人能帮帮我吗?

public void LoginForm_Paint(object sender, PaintEventArgs e)
{
    Graphics graphics = e.Graphics;
    Pen redPen = new Pen(Color.Red);
}
public bool ValidateTextBoxes(params TextBox[] textBoxes)
{
    foreach (var textBox in textBoxes)
    {
        if (textBox.Text.Equals(""))
        {
            textBox.BackColor = Color.Red;
            return false;
        }
    }
    return true;
}

我想这样使用它(就像在LoginForm):

public void LoginForm_Paint(object sender, PaintEventArgs e)
{
    Graphics graphics = e.Graphics;
    Pen redPen = new Pen(Color.Red);
}
public bool ValidateTextBoxes(params TextBox[] textBoxes)
{
    foreach (var textBox in textBoxes)
    {
        if (textBox.Text.Equals(""))
        {
            graphics.DrawRectangle(redPen, textBox.Location.X,
                          textBox.Location.Y, textBox.Width, textBox.Height);
            return false;
        }
    }
    return true;
}

但它不是这样工作的。它不能识别我创建的实例Graphics graphics = e.Graphics;

绘制矩形作为文本框边框

对象graphics不被"识别",因为它是在您使用它的方法之外定义的,即在LoginForm_Paint中本地定义并在ValidateTextBoxes中使用。

您应该使用您正在绘制的文本框的图形对象:

public bool ValidateTextBoxes(params TextBox[] textBoxes)
{
    foreach (var textBox in textBoxes)
    {
        if (textBox.Text.Equals(""))
        {
            Graphics graphics = textBox.CreateGraphics();
            graphics.DrawRectangle(redPen, textBox.Location.X,
                          textBox.Location.Y, textBox.Width, textBox.Height);
            return false;
        }
    }
    return true;
}