Csharp/C#教程:GetWindowText()抛出错误而不被try / catch捕获分享


GetWindowText()抛出错误而不被try / catch捕获

当我为GetWindowText运行下面的代码时,我得到以下错误作为内部exception抛出:

{“尝试读取或写入受保护的内存。这通常表示其他内存已损坏。”}

[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) } 

我有两个问题:

  1. 为什么错误没有被try catch捕获?

  2. 知道除了使用try / catch之外,当它遇到这种类型的错误时我怎么能阻止程序崩溃

干杯

1。

有一些例外是无法捕获的。 一种类型是StackOverflow或OutOfMemory,因为实际上没有内存可供分配给运行的处理程序。 另一种类型是通过Windows OS传送到CLR的类型。 此机制称为结构化exception处理。 这些exception可能非常糟糕,因为CLR无法确定其自身的内部状态是否一致,有时称为损坏的状态exception。 在.Net 4中,托管代码默认不处理这些exception。

上面的消息来自AccessViolationException,这是一种损坏的状态exception。 发生这种情况是因为您正在调用一个非托管方法,该方法正在写入缓冲区的末尾。 请参阅有关可能处理这些exception的文章。

2。

这里的示例代码是否有效? 您需要确保非托管代码不会写入StringBuilder缓冲区的末尾。

 public static string GetText(IntPtr hWnd) { // Allocate correct string length first int length = GetWindowTextLength(hWnd); StringBuilder sb = new StringBuilder(length + 1); GetWindowText(hWnd, sb, sb.Capacity); return sb.ToString(); } 

由于您为GetWindowText提供的参数,调用这些外部方法可能会导致问题。 我想你应该尝试以下方法:

上述就是C#学习教程:GetWindowText()抛出错误而不被try / catch捕获分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 try{ int strLength = NativeMethods.GetWindowTextLength(wndHandle); var wndStr = new StringBuilder(strLength + 1); GetWindowText(wndHandle, wndStr, wndStr.Capacity); } catch(Exception e){ LogError(e) } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/956309.html

(0)
上一篇 2021年11月20日
下一篇 2021年11月20日

精彩推荐