C# 修改窗体边框颜色

本文介绍如何使用 C# 和 Win32 API 修改窗体的边框颜色。

代码示例

以下代码演示如何将窗体的边框颜色修改为红色:csharpusing System;using System.Drawing;using System.Runtime.InteropServices;using System.Windows.Forms;

namespace WindowsFormsApp{ public partial class MainForm : Form { private const int WM_NCPAINT = 0x85; private const int HT_CAPTION = 0x2; private const int WM_NCCALCSIZE = 0x83;

    [DllImport('user32.dll')]        private static extern IntPtr GetWindowDC(IntPtr hWnd);        [DllImport('user32.dll')]        private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);        [DllImport('user32.dll')]        private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);        [DllImport('user32.dll')]        private static extern int GetWindowLong(IntPtr hWnd, int nIndex);

    public MainForm()        {            InitializeComponent();

        // 设置窗体边框颜色            SetBorderColor(Color.Red);        }

    protected override void WndProc(ref Message m)        {            base.WndProc(ref m);

        if (m.Msg == WM_NCPAINT || m.Msg == WM_NCCALCSIZE)            {                // 重新设置窗体边框颜色                SetBorderColor(Color.Red);            }        }

    private void SetBorderColor(Color color)        {            int colorRef = color.R | (color.G << 8) | (color.B << 16);            IntPtr hDC = GetWindowDC(this.Handle);            int style = GetWindowLong(this.Handle, -16);            style |= 0x80000;            SetWindowLong(this.Handle, -16, style);            ReleaseDC(this.Handle, hDC);            ReleaseDC(this.Handle, hDC);            Invalidate();        }    }}

代码说明

  1. 导入 Win32 API: 使用 DllImport 特性导入 GetWindowDCReleaseDCSetWindowLongGetWindowLong 函数。2. 设置边框颜色:SetBorderColor 方法中,首先获取窗体的设备上下文,然后使用 SetWindowLong 函数修改窗体样式,最后释放设备上下文并刷新窗体。3. 处理窗体消息: 重写 WndProc 方法,在 WM_NCPAINTWM_NCCALCSIZE 消息触发时重新设置边框颜色,确保边框颜色在窗体重绘时保持一致。

使用方法

  1. 将上述代码复制到你的 C# 窗体应用程序项目中。2. 在窗体的构造函数中调用 SetBorderColor 方法,传入你想要的边框颜色即可。

注意

  • 该方法需要使用 System.DrawingSystem.Runtime.InteropServicesSystem.Windows.Forms 命名空间。* 你需要根据你的需要修改示例代码中的颜色值。

希望本文对你有所帮助!

C# 修改窗体边框颜色 - Win32 API 实现

原文地址: https://www.cveoy.top/t/topic/obq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录