本文主要是介绍Unity WindowsSDK对接之win窗口句柄、进程、常见问题处理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
持续更新中…
常用代码
1】查找窗口句柄
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);// 查找记事本窗口句柄
IntPtr hWnd = FindWindow("Notepad", null);
2】获取当前进程
Process curProcess = Process.GetCurrentProcess();
int curProId = curProcess.Id; // 获取当前进程id// 直接杀掉进程
curProcess.Kill();
curProcess.WaitForExit();// 获取所有进程
Process[] process = Process.GetProcesses();
3】获取当前窗口句柄【高级】
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using LR;
using AOT;public delegate bool WNDENUMPROC(IntPtr hwnd, uint lParam);[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);// 如果unity是IL2Cpp的话,必须静态才能合法传到c++层
[MonoPInvokeCallback(typeof(WNDENUMPROC))]
public static bool EnumWindowCallBack(IntPtr hwnd, uint lParam)
{uint id = 0;if (GetParent(hwnd) == IntPtr.Zero){GetWindowThreadProcessId(hwnd, ref id);// 如果这个进程id == 当前进程id,则返回窗口句柄if (id == lParam){m_GameProcessID = hwnd;return false;}}return true;
}// 获取当前进程窗口句柄
public static IntPtr GetProcessWnd()
{uint pid = (uint)Process.GetCurrentProcess().Id; // 当前进程 ID // 遍历所有win枚举,找bool bResult = EnumWindows(EnumWindowCallBack , pid);m_GameProcessID = (!bResult && Marshal.GetLastWin32Error() == 0) ? m_GameProcessID : IntPtr.Zero;return m_GameProcessID;
}
问题处理
问题1:获取当前窗口句柄时抛出异常:NotSupportedException: IL2CPP does not support marshaling
delegates that point to instance methods to native code
原因:在il2cpp的方式下,不能直接传实例到c++层面, 传过去的必须是静态方法才行【把自定义函数传递给 C++非托管代码】。 mono的没问题,纯C#的也没问题。 以下解决方案(加静态,加特性都是必须的)ok的。
参考1:https://garry.tv/steamworks-and-il2cpp
参考2:https://www.jianshu.com/p/fa513f9d3a1c
问题2:游戏出现GetThreadContext failed报错 Unity开发
解决方案
1.检查是否有360。有的情况(1)简单方案:卸载360。(2)专业方案:将游戏exe添加到360信任名单中
解释:360会将一些模拟按键视为木马,然后游戏运行一般直接闪退。
2.检查防火墙。专业方案:将游戏exe加入防火墙允许应用的列表中,勾选专用和公用。
解释:无。关了防火墙还会有问题,然后将exe加入允许列表就没碰到了。玄学。
参考:https://blog.csdn.net/wanfping123/article/details/103426716
问题3:打出来的包 权限是高(双击打开必须要管理员权限,有的因为电脑设置不会提示),要改成中?
跳转博文
这篇关于Unity WindowsSDK对接之win窗口句柄、进程、常见问题处理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!