C# Winform 实现窗体无系统边框,但是具有系统边框的所有功能
作者:野牛程序员:2024-01-07 08:50:18C#阅读 2640
可以通过以下C#代码在WinForm中实现窗体无系统边框但具有系统边框功能:
using System; using System.Runtime.InteropServices; using System.Windows.Forms; public class CustomForm : Form { private const int WM_NCHITTEST = 0x0084; private const int HT_CAPTION = 0x2; private const int HT_CLIENT = 0x1; private const int WM_SYSCOMMAND = 0x112; private const int SC_MOVE = 0xF010; [DllImportAttribute("user32.dll")] public static extern int ReleaseCapture(); [DllImportAttribute("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == WM_NCHITTEST) { int result = HitTestNCA(m.HWnd, m.WParam, m.LParam); if (result == HT_CLIENT) { m.Result = new IntPtr(HT_CAPTION); } } else if (m.Msg == WM_SYSCOMMAND && (m.WParam.ToInt32() & 0xfff0) == SC_MOVE) { ReleaseCapture(); SendMessage(Handle, WM_SYSCOMMAND, SC_MOVE + HT_CAPTION, 0); } } private int HitTestNCA(IntPtr hwnd, IntPtr wparam, IntPtr lparam) { int x = (int)(lparam.ToInt64() & 0xFFFF); int y = (int)((lparam.ToInt64() & 0xFFFF0000) >> 16); Point clientPos = PointToClient(new Point(x, y)); if (clientPos.X >= 0 && clientPos.X < ClientSize.Width && clientPos.Y >= 0 && clientPos.Y < ClientSize.Height) { return HT_CLIENT; } return HT_CAPTION; } } class Program { static void Main() { Application.Run(new CustomForm()); } }
这段代码创建了一个自定义的窗体类CustomForm
,并覆盖了WndProc
方法以处理窗体消息。此代码允许用户在无系统边框的窗体上移动窗体,并保留了具有系统边框的所有功能。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892