开发应用程序时,窗体的标题内容非常重要,窗体标题中的文字主要用来介绍当前窗体,窗体可以主要为用户提供哪些功能、窗体状态或名称等信息,在窗体中标题栏中的文字一般都是居左显示的,但是,某些特殊情况下,会遇到将标题栏中的文字居右显示的需求,那么,在c#编程语言中,遇到这个问题该如何解决呢?
关键代码:
public partial class CustomTitleBarForm : Form { private const int CS_DROPSHADOW = 0x20000; private const int WM_NCCALCSIZE = 0x0083; private const int WM_NCPAINT = 0x0085; public CustomTitleBarForm() { InitializeComponent(); // 移除默认标题栏 this.FormBorderStyle = FormBorderStyle.None; this.Padding = new Padding(1, 0, 1, 1); // 模拟边框 // 创建自定义标题栏 Panel titleBar = new Panel(); titleBar.Dock = DockStyle.Top; titleBar.Height = 30; titleBar.BackColor = SystemColors.Control; titleBar.MouseDown += TitleBar_MouseDown; this.Controls.Add(titleBar); // 添加右对齐标题文本 Label titleLabel = new Label(); titleLabel.Text = this.Text; titleLabel.Dock = DockStyle.Fill; titleLabel.TextAlign = ContentAlignment.MiddleRight; titleLabel.Margin = new Padding(0, 0, 10, 0); titleLabel.MouseDown += TitleBar_MouseDown; titleBar.Controls.Add(titleLabel); // 添加关闭按钮 Button closeButton = new Button(); closeButton.Text = "X"; closeButton.FlatStyle = FlatStyle.Flat; closeButton.FlatAppearance.BorderSize = 0; closeButton.Width = 30; closeButton.Dock = DockStyle.Right; closeButton.Click += CloseButton_Click; titleBar.Controls.Add(closeButton); // 添加最小化按钮 Button minimizeButton = new Button(); minimizeButton.Text = "-"; minimizeButton.FlatStyle = FlatStyle.Flat; minimizeButton.FlatAppearance.BorderSize = 0; minimizeButton.Width = 30; minimizeButton.Dock = DockStyle.Right; minimizeButton.Click += MinimizeButton_Click; titleBar.Controls.Add(minimizeButton); } // 处理标题栏拖动 private void TitleBar_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { ReleaseCapture(); SendMessage(this.Handle, 0xA1, 0x2, 0); } } private void CloseButton_Click(object sender, EventArgs e) { this.Close(); } private void MinimizeButton_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; } // 引入必要的Win32 API [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern bool ReleaseCapture(); // 重写CreateParams添加阴影效果 protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ClassStyle |= CS_DROPSHADOW; return cp; } } // 重写WndProc处理非客户区绘制 protected override void WndProc(ref Message m) { if (m.Msg == WM_NCCALCSIZE && m.WParam.ToInt32() == 1) { return; } if (m.Msg == WM_NCPAINT) { // 绘制边框 Rectangle rect = new Rectangle(0, 0, this.Width, this.Height); ControlPaint.DrawBorder( System.Drawing.Graphics.FromHwnd(m.HWnd), rect, SystemColors.ControlDark, 1, ButtonBorderStyle.Solid, SystemColors.ControlDark, 1, ButtonBorderStyle.Solid, SystemColors.ControlDark, 1, ButtonBorderStyle.Solid, SystemColors.ControlDark, 1, ButtonBorderStyle.Solid); } base.WndProc(ref m); } }
评论