我这里有一个C#的窗体基类,今天添加了窗体阴影效果的代码。运行后窗体有阴影效果,但是当我点击其它地方,或者最小化该程序后,阴影效果就消失了。
请高手将该代码进行修改,让该窗体基类能够显示窗体阴影效果。
https://files.cnblogs.com/files/lzhdim/Src.rar?t=1704706040&download=true
你可以使用 Form 的 WmNcPaint 和 WmNcCalcSize 消息来自定义非客户区(Non-client area)的绘制,从而实现窗体阴影效果。以下是一个简单的例子:
csharp
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class ShadowForm : Form
{
const int CS_DropSHADOW = 0x20000;
const int GCL_STYLE = -26;
const int WS_MINIMIZEBOX = 0x20000;
const int WS_MAXIMIZEBOX = 0x10000;
const int WS_SYSMENU = 0x80000;
const int WS_SIZEBOX = 0x40000;
[DllImport("user32.dll")]
public static extern int GetClassLong(IntPtr hwnd, int nIndex);
[DllImport("user32.dll")]
public static extern int SetClassLong(IntPtr hwnd, int nIndex, int dwNewLong);
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ClassStyle |= CS_DropSHADOW;
return cp;
}
}
public ShadowForm()
{
this.FormBorderStyle = FormBorderStyle.Sizable;
this.StartPosition = FormStartPosition.CenterScreen;
this.Size = new Size(300, 200);
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
switch (m.Msg)
{
case 0x83: // WM_NCCALCSIZE
if (m.WParam.ToInt32() == 1)
{
int style = GetClassLong(this.Handle, GCL_STYLE);
style = style & ~(WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_SYSMENU | WS_SIZEBOX);
SetClassLong(this.Handle, GCL_STYLE, style);
}
break;
case 0x85: // WM_NCPAINT
IntPtr hdc = GetWindowDC(m.HWnd);
if (hdc.ToInt32() != 0)
{
using (Graphics g = Graphics.FromHdc(hdc))
{
g.FillRectangle(Brushes.DarkGray, new Rectangle(0, 0, this.Width, 5));
g.FillRectangle(Brushes.DarkGray, new Rectangle(0, 0, 5, this.Height));
g.FillRectangle(Brushes.DarkGray, new Rectangle(this.Width - 5, 0, 5, this.Height));
g.FillRectangle(Brushes.DarkGray, new Rectangle(0, this.Height - 5, this.Width, 5));
}
ReleaseDC(m.HWnd, hdc);
}
break;
}
}
[DllImport("user32.dll")]
static extern IntPtr GetWindowDC(IntPtr hWnd);
[DllImport("user32.dll")]
static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
}
class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new ShadowForm());
}
}
这是一个简单的窗体,使用 WM_NCCALCSIZE 和 WM_NCPAINT 消息在非客户区绘制了一个灰色的矩形框,模拟阴影效果。你可以根据自己的需求调整颜色、大小等参数。希望这能帮到你,如果有其他问题,请随时问。
我不要例子,,,最好直接更改我那个C#的窗体基类,使其能够正常运行。。。
你这个this.FormBorderStyle = FormBorderStyle.Sizable;默认就带阴影的啊,还绘制啥?