首页 > 解决方案 > 失去焦点时自定义文本框值消失

问题描述

我创建了一个自定义文本框,它是:

我目前遇到的问题是,每当我在文本框中输入一个值时,该值看起来都很好,但是当我在其区域之外单击时,文本会像这样消失: 在此处输入图像描述

我可以取回文本的唯一方法是在文本框中单击,我还有一些根本没有出现的占位符文本,但这是次要问题。

这是代码:

构造函数

    public TQSTextBox([Optional] bool rounded ,[Optional] int roundedRadius) : base()
    {
      try
      {
        if (RoundedEdge == false && roundedRadius == 0) { throw new Exception("Failed to Construct a rounded TQSTextBox."); }

        // enable the OnPaint event
        SetStyle(ControlStyles.UserPaint, true);
        RoundedEdge = rounded;
        RoundedEdgeRadius = roundedRadius;

        BorderStyle = BorderStyle.FixedSingle;
        Height = DefaultSize.Height + 5;
        Width = 121;
        TextAlign = HorizontalAlignment.Center;
        GotFocus += HandleFocus;
        LostFocus += HandleLostFocus;
        DoubleBuffered = true;
      }
      catch (Exception e)
      {
        Log.Msg(e.Message);

        RoundedEdge = false;
        RoundedEdgeRadius = 0;

        BorderStyle = BorderStyle.FixedSingle;
        Width = 121;
      }
    }

图形路径法

    private GraphicsPath GetRoundedPath()
    {
      GraphicsPath path = new GraphicsPath();

      path.StartFigure();
      path.AddArc(new Rectangle(0, 0, RoundedEdgeRadius, RoundedEdgeRadius), 180, 90);
      path.AddLine(RoundedEdgeRadius, 0, Width - RoundedEdgeRadius, 0);
      path.AddArc(new Rectangle(Width - RoundedEdgeRadius, 0, RoundedEdgeRadius, RoundedEdgeRadius), -90, 90);
      path.AddLine(Width, RoundedEdgeRadius, Width, Height - RoundedEdgeRadius);
      path.AddArc(new Rectangle(Width - RoundedEdgeRadius, Height - RoundedEdgeRadius, RoundedEdgeRadius, RoundedEdgeRadius), 0, 90);
      path.AddLine(Width - RoundedEdgeRadius, Height, RoundedEdgeRadius, Height);
      path.AddArc(new Rectangle(0, Height - RoundedEdgeRadius, RoundedEdgeRadius, RoundedEdgeRadius), 90, 90);
      path.CloseFigure();

      return path;
    }

OnPaint 事件

    protected override void OnPaint(PaintEventArgs e)
    {   
      Graphics g = e.Graphics;
      g.SmoothingMode = SmoothingMode.AntiAlias;

      if (RoundedEdge)
      {
        g.DrawPath(new Pen(new SolidBrush(Color.LightGray), 3), GetRoundedPath());
        if (Clicked)
        {
          g.DrawPath(new Pen(new SolidBrush(Color.Gray), 3), GetRoundedPath());
        }
      }      
      base.OnPaint(e);
    }

焦点/失去焦点事件

    private void HandleLostFocus(object sender, EventArgs e)
    {
      Clicked = false;
      Invalidate();
    }

标签: c#winformsuser-interfaceeventsgraphicspath

解决方案


推荐阅读