c# 获得一个程序的窗口句柄,并且修改它的标题

按下BUTTON1的时候
以获取calc.exe 将窗口标题计算器 改成 我的计算器
最简单的代码 提供一下 ,能用就给分了
最新回答
绝命小红帽

2024-11-28 11:22:46

第一步:获取目标窗口句柄

首先引用命名空间:

using System.Runtime.InteropServices;
 [DllImport("user32.dll", EntryPoint = "FindWindow")]
        public static extern IntPtr FindWindow(
            string lpClassName,
            string lpWindowName
        );

利用FindWindow获得目标窗口句柄

第一个参数是类名,第二个参数是窗口原来的标题

以下代码则是获得目标窗口代码:

 IntPtr window = FindWindow(null,"Microsoft SQL Server Management Studio");//我这里是以SQL为例

第二步:改变窗口标题

 [DllImport("user32.dll", EntryPoint = "SetWindowText")]
        public static extern int SetWindowText(
            IntPtr hwnd,
            string lpString
        );

以下代码则是改变目标句柄的窗口标题:

SetWindowText(window,"你好啊");

Ok,窗口标题成功修改了!!!!

附加根据进程名称修改标题:

Process [] ps= Process.GetProcessesByName("Ssms");//根据进程名称获得进程数组
            foreach(Process p in ps)//遍历进程
            {
                SetWindowText(p.MainWindowHandle, "Microsoft SQL Server Management Studio免费共享版");
            }
三生路

2024-11-28 13:22:02


//add
using System.Runtime.InteropServices; 

namespace ModifyTitle
{
    public partial class Form1 : Form
    {
        [DllImport("user32.dll", EntryPoint = "FindWindowA", CharSet = CharSet.Ansi)]
        public static extern int FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", EntryPoint = "SetWindowText", CharSet = CharSet.Ansi)]
        public static extern int SetWindowText(int hwnd, string lpString);


        public Form1()
        {
            InitializeComponent();
            //启动计算器
            System.Diagnostics.Process.Start("calc.exe");
        }

        private void button1_Click(object sender, EventArgs e)
        {            
            int lHwnd = FindWindow(null, "计算器");
            while (lHwnd != 0)
            {
                SetWindowText(lHwnd, "我的计算器");
                lHwnd = FindWindow(null, "计算器");
            }
        }


    }
}
追问
能不能以进程名或者窗口句柄修改 你这个方法是通过名字修改的对我没有用啊
纯家小可爱

2024-11-28 10:22:09

通过进程名获取进程句柄就可以了!!!
一花一树开

2024-11-28 16:08:39

this.Text = "标题";