如何在C#中的TextBox_TextChanged事件中调用Form1_Paint事件?

时间:2019-05-08 11:24:14

标签: c# .net winforms

我有一个TextBox的名字,它需要用户的文件夹路径。我正在指定文件夹中搜索文件。如果找到,它将边框颜色更改为绿色,如果找不到,则会将边框颜色更改为红色。

我在线找到了一些代码/帮助,mainForm_Paint事件正在触发,但是即使成功执行了所有行,边框也不会改变。

这是我的代码:

private void PathTextBox_TextChanged(object sender, EventArgs e)
{
    try
    {
        if (!(String.IsNullOrEmpty(pathTextBox.Text) || String.IsNullOrWhiteSpace(pathTextBox.Text)))
        {
            string pathFolder = pathTextBox.Text;
            DirectoryInfo directoryInfo = new DirectoryInfo(pathFolder);
            string pathParent = directoryInfo.Parent.FullName;
            if (pathFolder.EndsWith("Text") && pathParent.ToLower().EndsWith("ops"))
            {
                string textFolder = Path.Combine(pathParent, "Text");
                Regex filePattern = new Regex("\\d{13}");
                string getxHTML = "";
                getxHTML = Directory.GetFiles(textFolder, "*.xhtml", SearchOption.TopDirectoryOnly)
                                           .Where(fileName => filePattern.IsMatch(Path.GetFileNameWithoutExtension(fileName))).FirstOrDefault();
                if (!(String.IsNullOrEmpty(getxHTML) || String.IsNullOrWhiteSpace(getxHTML)))
                {
                    foundValue = true;
                }
                else
                {
                    foundValue = false;
                }
            }
            else
            {
                foundValue = false;
            }
            pathTextBox.Parent.Invalidate();
        }
    }
    catch (Exception ex)
    {
        foundValue = false;
        pathTextBox.Parent.Invalidate();
    }
}

private void MainForm_Paint(object sender, PaintEventArgs e)
{
    if (foundValue)
    {
        pathTextBox.BorderStyle = BorderStyle.None;
        Pen p = new Pen(Color.Green);
        Graphics g = e.Graphics;
        int variance = 3;
        g.DrawRectangle(p, new Rectangle(pathTextBox.Location.X - variance,
                                         pathTextBox.Location.Y - variance,
                                         pathTextBox.Width + variance,
                                         pathTextBox.Height + variance));
    }
    else
    {
        pathTextBox.BorderStyle = BorderStyle.None;
        Pen p = new Pen(Color.Red);
        Graphics g = e.Graphics;
        int variance = 3;
        Rectangle textBoxRectangle = new Rectangle(pathTextBox.Location.X - variance,
                                                   pathTextBox.Location.Y - variance,
                                                   pathTextBox.Width + variance,
                                                   pathTextBox.Height + variance);
        g.DrawRectangle(p, textBoxRectangle);
    }
}

0 个答案:

没有答案