第一步:获取目标窗口句柄
首先引用命名空间:
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免费共享版");
}
//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, "计算器");
}
}
}
}
通过进程名获取进程句柄就可以了!!!
this.Text = "标题";