【问题标题】:Custom control error自定义控制错误
【发布时间】:2013-07-20 00:48:59
【问题描述】:

我正在开发这个自定义控件。 (我对这部分编程非常陌生。)我正在开发一个应用程序,当用户在我自己的自定义控件中输入输入时,它必须能够格式化数学表达式。这就是我希望控件的外观(此图像是在 Photoshop 中制作的):

我不会解释我希望它具有的行为,因为这对你没有帮助,但我的想法是它不基于任何 Windows 控件

这是我已有的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Support.Components
{
    public partial class PartialExpressionEditor : Control
    {
        public PartialExpressionEditor()
        {
            InitializeComponent();
        }

        protected override void OnPaint(PaintEventArgs pe)
        {
           base.OnPaint(pe);

           Brush background = Brushes.White;
           pe.Graphics.FillRectangle(background, ClientRectangle);
           background.Dispose();
        }
    }
}

当我尝试将它放入我的表单时,我得到了这个错误对话框:

问题出在哪里?或者为什么会出现这个错误?

【问题讨论】:

  • 你的类显示你的控件继承自Control,但你为什么说it's not based on any Windows control
  • 顺便说一句,您的代码对我来说似乎不错,除了我会使用 using(Brush background = Brushes.White){....} 而不是像您那样直接调用 Dispose()。您可以尝试删除Dispose() 或至少尝试使用using 样式吗?
  • “它不基于任何 Windows 控件”,我的意思是它不是按钮、文本框或复选框等...

标签: c# winforms custom-controls


【解决方案1】:

我认为问题在于您正在处理系统刷:

// background.Dispose();

因为你没有创建它:

Brush background = Brushes.White;

使用您自己处置的刷子:

using (SolidBrush br = new SolidBrush(Color.White)) {
  pe.Graphics.FillRectangle(br, this.ClientRectangle);
}

您可能必须退出 Visual Studio 才能恢复您的 Brushes.White 笔刷。

【讨论】:

  • 我的问题不在于我运行应用程序时!当我尝试从 VS2010 的工具箱中删除表单上的控件时会发生这种情况
  • @Victor 不会改变我的答案。使用设计器中的控件将运行绘制事件。
  • 编辑后,代码生效!非常感谢!我现在可以...开始编写我的控件:))
猜你喜欢
  • 1970-01-01
  • 2014-12-18
  • 2020-03-13
  • 2017-12-03
  • 1970-01-01
  • 2013-01-15
  • 1970-01-01
  • 2018-06-11
  • 2014-03-07
相关资源
最近更新 更多