You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中修改其他程序的FormBorderStyle为Sizable

修改外部程序窗口边框为可调整大小(Sizable)

要修改其他程序窗口的边框样式为可调整大小,本质是通过Windows API修改窗口的原生样式——.NET的FormBorderStyle.Sizable对应原生窗口的WS_THICKFRAME样式,搭配WS_CAPTION(标题栏)才能实现完整的可调整边框效果。

实现步骤与代码

首先需要引入必要的Windows API函数,通过修改窗口样式位来实现:

using System;
using System.Runtime.InteropServices;

public class WindowStyleEditor
{
    // 窗口样式索引与常量
    private const int GWL_STYLE = -16;
    private const int WS_THICKFRAME = 0x00040000; // 允许调整窗口大小的边框样式
    private const int WS_CAPTION = 0x00C00000;     // 保留标题栏(可调整边框通常依赖标题栏)

    // 获取当前窗口样式
    [DllImport("user32.dll", SetLastError = true)]
    private static extern IntPtr GetWindowLongPtr(IntPtr hWnd, int nIndex);

    // 设置新的窗口样式
    [DllImport("user32.dll", SetLastError = true)]
    private static extern IntPtr SetWindowLongPtr(IntPtr hWnd, int nIndex, IntPtr dwNewLong);

    // 刷新窗口使样式生效
    [DllImport("user32.dll")]
    private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

    /// <summary>
    /// 将目标窗口设置为可调整大小
    /// </summary>
    /// <param name="hWnd">目标窗口句柄</param>
    /// <returns>修改是否成功</returns>
    public static bool SetWindowSizable(IntPtr hWnd)
    {
        if (hWnd == IntPtr.Zero) return false;

        // 获取当前窗口样式
        IntPtr currentStyle = GetWindowLongPtr(hWnd, GWL_STYLE);
        if (currentStyle == IntPtr.Zero) return false;

        // 添加可调整边框与标题栏样式
        IntPtr newStyle = (IntPtr)(currentStyle.ToInt64() | WS_THICKFRAME | WS_CAPTION);

        // 应用新样式
        IntPtr result = SetWindowLongPtr(hWnd, GWL_STYLE, newStyle);
        if (result == IntPtr.Zero) return false;

        // 强制窗口刷新样式
        const uint SWP_FRAMECHANGED = 0x0020;
        const uint SWP_NOMOVE = 0x0002;
        const uint SWP_NOSIZE = 0x0001;
        return SetWindowPos(hWnd, IntPtr.Zero, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE);
    }
}

使用示例

如果需要通过窗口标题获取目标窗口句柄,可以搭配FindWindow API:

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

// 示例:找到标题为"测试窗口"的外部程序窗口并修改
IntPtr targetWindow = FindWindow(null, "测试窗口");
if (targetWindow != IntPtr.Zero)
{
    bool isSuccess = WindowStyleEditor.SetWindowSizable(targetWindow);
    Console.WriteLine(isSuccess ? "边框样式修改成功" : "边框样式修改失败");
}

注意事项

  • 部分程序需要管理员权限才能修改其窗口样式,运行你的程序时需确保权限足够。
  • 某些自定义边框的窗口可能不兼容此修改,需要根据目标程序的窗口特性调整样式位。
  • 64位环境下必须使用SetWindowLongPtr,32位环境可兼容使用SetWindowLong,但SetWindowLongPtr是更通用的选择。

内容的提问来源于stack exchange,提问作者HaRuonl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 16:40:53