×

在dotnet中开发控件(三)

Kalet Kalet 发表于2009-03-20 12:00:14 浏览188 评论0

抢沙发发表评论

在dotnet中开发控件(三)



在dotnet中开发控件(三)

       老实说,把msdn研究完,发现一个事实,在vs 2005中继承一个已有控件进行进行扩展很简单,哪怕什么设计时的问题也容易解决。


       其实最郁闷的问题还是自绘控件的问题。本来我想去DevExpress的代码中找出点蛛丝马迹来,但是,DevExpress的代码实在嵌套层次太多了。加上我逆向工程没有得到类图。郁闷得不得了。搞了半天,搞了个半成品。代码如下:


namespace DevApp
{


    [ToolboxItem(true),DesignerCategory("tianmo")]
    public partial class MyTextBox : System.Windows.Forms.TextBox
    {



        public MyTextBox()
        {
            InitializeComponent();
            this.SetStyle(ControlStyles.UserPaint, true);
            this.BorderStyle = BorderStyle.None;
        }


 


        protected override void OnPaint(PaintEventArgs pe)
        {


            // TODO: 在此处添加自定义绘制代码
            Graphics g = pe.Graphics;


            //g.DrawRectangle(new Pen(System.Drawing.Color.Red,0.5f), new Rectangle(0, 0, this.Width-1, this.Height-1));


            ControlPaint.DrawBorder(g, new Rectangle(0, 0, this.Width - 1, this.Height - 1), System.Drawing.Color.Red, ButtonBorderStyle.Solid);
            // 调用基类 OnPaint
            base.OnPaint(pe);

在dotnet中开发控件(三)

        }


    }
}


本来,只重载个OnPaint一点效果都没有,多亏大侠支持,才晓得要SetStyle,还要把BorderStyle设为None。不然,不用。但是,就是如此,还有大问题。


       有人推荐不要重载OnPaint方法。在WndProc方法中推截消息比较好。我试了,代码如下:


        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);


            switch (m.Msg)
            {
                case Win32Helper.WM_NCPAINT:
                case Win32Helper.WM_PAINT:
                    {
                        Graphics g = this.CreateGraphics();
                        Rectangle rc = this.ClientRectangle;
                        rc.Height = rc.Height - 1;
                        rc.Width = rc.Width - 1;


                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                        g.DrawRectangle(new Pen(System.Drawing.Color.Red, 1), rc);
                        break;
                    }
            }


        }

在dotnet中开发控件(三)

其中Win32Helper是我在网上找的一位大侠写的类,里面封装了所有的关于窗体、控件的消息。蛮有用的。但是,用这种方法,我仍然没能解决问题。



群贤毕至

访客