重写.net的winfrom控件

这几天做winfrom项目,为个改变按钮样式,使用到了重写控件技术。

开始实现自定义button的时候,使用的是OnPaint方式,但出现的一个现象解决不了。就是当有其它窗口遮挡住自定义button后,再关闭遮挡窗口后,自定义button不进行重绘,估计那个地方有问题吧。
后来考虑到象textbox这咱控件不能通过OnPaint进行重写,

最后改用拦截系统重绘消息的方式解决了这个问题。
先导入user32.dll
[System.Runtime.InteropServices.DllImport("user32.dll ")]

  static extern IntPtr GetWindowDC(IntPtr hWnd);

  [System.Runtime.InteropServices.DllImport("user32.dll ")]

   static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);

重写WndProc
protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            //判断是否是重绘消息
            if (m.Msg == 0xf || m.Msg == 0x133)
            {
                IntPtr hDC = GetWindowDC(m.HWnd);

                if (hDC.ToInt32() == 0)
                {
                    return;
                }
                try
                {
                    System.Drawing.Graphics g = Graphics.FromHdc(hDC);
                    System.Drawing.Rectangle rect = new Rectangle(0, 0, this.Width, this.Height);
                    System.Windows.Forms.PaintEventArgs e = new PaintEventArgs(g, rect);
                    this.DrawBackgroundColor(e);
                    this.DrawForeColor(e);
                    this.DrawText(e);
                    //返回结果  
                    m.Result = IntPtr.Zero;
                    //释放  
                    ReleaseDC(m.HWnd, hDC);
                }
                catch
                {
                }
            }
        }

你可能感兴趣的:(重写.net的winfrom控件)