枚举Windows进程时偶发An item with the same key异常求助
问题原因与解决办法
异常'An item with the same key'是因为你调用dictWindows.Add(hWnd, stringBuilder.ToString)时,同一个hWnd句柄被多次尝试添加到字典中——字典的键必须唯一,重复添加就会触发这个异常。
解决方式
直接在添加前检查字典中是否已存在该键,或者改用赋值方式覆盖已有键:
方式一:检查后添加(保留原有键值,不覆盖)
修改代码中添加字典的部分:
If Not dictWindows.ContainsKey(hWnd) Then dictWindows.Add(hWnd, stringBuilder.ToString) End If
方式二:直接赋值(覆盖原有键值)
如果允许后续获取的窗口文本覆盖之前的记录,也可以直接用字典的Item属性:
dictWindows(hWnd) = stringBuilder.ToString
修改后的完整函数示例
Private Function enumWindowsInternal(ByVal hWnd As IntPtr, ByVal lParam As Integer) As Boolean Try If hWnd <> hShellWindow Then Dim windowPid As UInt32 If Not IsWindowVisible(hWnd) Then Return True End If Dim length As Integer = GetWindowTextLength(hWnd) If length = 0 Then Return True End If GetWindowThreadProcessId(hWnd, windowPid) If windowPid <> currentProcessID Then Return True End If Dim stringBuilder As New StringBuilder(length) GetWindowText(hWnd, stringBuilder, length + 1) ' 替换原Add语句,用检查后添加的方式 If Not dictWindows.ContainsKey(hWnd) Then dictWindows.Add(hWnd, stringBuilder.ToString) End If End If Return True Catch ex As Exception writeExeption(ex) End Try Return False End Function
补充说明
偶发异常的原因可能是窗口枚举过程中,系统对同一个窗口句柄进行了多次回调,或者窗口短暂销毁重建后复用了相同句柄。通过上述两种方式,都能彻底避免键重复的问题。
内容的提问来源于stack exchange,提问作者Luiz
相关产品推荐
相关产品推荐

