在c#脚本中如何获取游戏窗口句柄呢,一般都是通过调用windows系统dll里的函数来获取的。
1.先获取自己的进程id
2.再枚举此进程的所有窗口句柄
3.对比窗口句柄对应的窗口名称
4.如果窗口名称对应得上,则退出枚举循环
代码中得,游戏窗口句柄一般都是游戏的名称,你可以用窗口模式打开游戏,游戏的左上角显示的名称就是这里要填写的参数
如果是使用的IL2CPP,则用下面的代码,需要在委托函数的声明前面加上[MonoPInvokeCallback]
using System.Collections;
using System;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Text;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.IO;
[DllImport("user32.dll", SetLastError = true)]
public static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, uint lParam);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetParent(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, ref uint lpdwProcessId);
[DllImport("user32.dll")]
public static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int nMaxCount);
[DllImport("User32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
public static extern int MessageBox(IntPtr handle, String message, String title, int type);
[DllImport("kernel32.dll")]
public static extern void SetLastError(uint dwErrCode);
[DllImport("user32.dll")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
public delegate bool WNDENUMPROC(IntPtr hwnd, uint lParam);
IntPtr ptrWnd = IntPtr.Zero;
public static IntPtr GetProcessWnd()
{
uint pid = (uint)Process.GetCurrentProcess().Id; // 当前进程 ID
bool bResult = EnumWindows(OnWindowEnum, pid);
return (!bResult && Marshal.GetLastWin32Error() == 0) ? ptrWnd : IntPtr.Zero;
}
[MonoPInvokeCallback]
static BOOL OnWindowEnum(IntPtr hwnd, uint lParam)
{
uint id = 0;
if (GetParent(hwnd) == IntPtr.Zero)
{
GetWindowThreadProcessId(hwnd, ref id);
if (id == lParam) // 找到进程对应的主窗口句柄
{
int length = GetWindowTextLength(hwnd);
StringBuilder windowName = new StringBuilder(length + 1);
GetWindowText(hwnd, windowName, windowName.Capacity);
if (windowName.ToString().CompareTo("游戏窗口名称") == 0) {
ptrWnd = hwnd; // 把句柄缓存起来
SetLastError(0); // 设置无错误
return false; // 返回 false 以终止枚举窗口
}
}
}
return true;
}
IntPtr ptrWnd = GetProcessWnd();
if (ptrWnd == IntPtr.Zero)
ptrWnd = FindWindow(null, "游戏窗口名称");