日期:2014-05-16 浏览次数:21043 次
有时候,我们用paint重绘用户控件时,起不到作用,这个时候,我们可以通过获取进程,来重绘控件。
下面这个实例是重绘边框的颜色为红色,当边框的风格为FixedSingle的时候,来进行重绘操作。
/// <summary> /// 获得当前进程,以便重绘控件 /// </summary> /// <param name="hWnd"></param> /// <returns></returns> [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);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; } if (this.BorderStyle == BorderStyle.FixedSingle) { //边框Width为1个像素 System.Drawing.Pen pen = new Pen(Color.Red,1); //绘制边框 System.Drawing.Graphics g = Graphics.FromHdc(hDC); g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.DrawRectangle(pen, 0, 0, this.Width-1, this.Height-1); pen.Dispose(); } //返回结果 m.Result = IntPtr.Zero; //释放 ReleaseDC(m.HWnd, hDC); } }