当我运行下面的代码获取GetWindowText时,抛出以下错误作为内部异常:
{"尝试读取或写入受保护的内存。这通常是其他内存已损坏的迹象。"}
{"尝试读取或写入受保护的内存。这通常是其他内存已损坏的迹象。"}
[DllImport("user32.dll", EntryPoint = "GetWindowTextLength", SetLastError = true)]
internal static extern int GetWindowTextLength(IntPtr hwnd);
[DllImport("user32.dll", EntryPoint = "GetWindowText", SetLastError = true)]
internal static extern int GetWindowText(IntPtr hwnd, ref StringBuilder wndTxt, int MaxCount);
try{
int strLength = NativeMethods.GetWindowTextLength(wndHandle);
var wndStr = new StringBuilder(strLength);
GetWindowText(wndHandle, ref wndStr, wndStr.Capacity);
}
catch(Exception e){ LogError(e) }
我有两个问题:
为什么try catch没有捕获到错误?
除了使用try/catch之外,有什么办法可以防止程序在遇到这种类型的错误时崩溃?
谢谢!