现在的位置: 首页 > 综合 > 正文

VB.NET(VS2005) 使用API的尴尬 (垃圾回收器 FUCK API)

2013年08月26日 ⁄ 综合 ⁄ 共 2122字 ⁄ 字号 评论关闭

我们知道微软不提倡在VS2005里使用API,甚至取消了以前 VB里的 API文本工具,,

最近由于一个项目的需要,,需要用到一个API  : GetLastInputInfo (聪明的你肯定已经知道我要做什么了:)或许还有其他方法,但做人总要追求完美吧~)

 正常的代码是:     Private Declare Function GetLastInputInfo Lib "user32" (ByVal plii As LASTINPUTINFO) As Long ‘声明

          Public Structure LASTINPUTINFO

          Dim cbSize As Int32

          Dim dwTime As Int32

      End Structure

'使用。。API。

      Dim lastInputInfo As LASTINPUTINFO

     lastInputInfo.cbSize = Len(lastInputInfo)

Try

         Dim lostTime As String = ""

         If GetLastInputInfo(lastInputInfo) <> 0 Then

               lostTime &= thObject2.Target.dwTime

               MsgBox(lostTime)

         End If

Catch ex As Exception

           MsgBox(ex.ToString)

End Try

很不幸VS给了我一个内存写权限的错误。(Attempted to read or write protected memory. This is often an indication that other memory is corrupt) 分析,,VS垃圾回收机制惹得祸。。用VC6.0重写了一遍代码,,一切OK。。再一次 FUCK VB.NET2005

换代码如下:      Private Declare Function GetLastInputInfo Lib "user32" (ByVal plii As IntPtr) As Long ’重新定义为 IntPtr

<Runtime.InteropServices.StructLayout(Runtime.InteropServices.LayoutKind.Sequential)> _  ‘加了这句心里安心点     Public Structure LASTINPUTINFO

          Dim cbSize As Int32

          Dim dwTime As Int32

     End Structure

Private Sub  aa()

          Dim lastInputInfo As LASTINPUTINFO

          lastInputInfo.cbSize = Len(lastInputInfo)

        Dim thObject2 As Runtime.InteropServices.GCHandle = Runtime.InteropServices.GCHandle.Alloc(lastInputInfo, Runtime.InteropServices.GCHandleType.Pinned)         Dim tpObject2 As IntPtr = thObject2.AddrOfPinnedObject() '取得指向结构的指针         Try

              Dim lostTime As String = ""

             Dim ret As Long = GetLastInputInfo(tpObject2)

              If ret  <> 0 Then

                  lostTime &= thObject2.Target.dwTime

                MsgBox(lostTime)

              End If

          Catch ex As Exception

              MsgBox(ex.ToString)

          End Try

        '在使用完毕后一定要释放指针指向的内存块,让垃圾回收器可对这个内存块回收处理          If thObject2.IsAllocated Then

              thObject2.Free()

         End If

   end sub

添加一个按钮,点击一下,OK ,,收工~

 小记:      微软为什么不推荐我们在.NET中使用API呢?

           个人认为使用API很多时候要涉及到对内存的操作,需要人工对内存进行管理,然而.NET这个自大的家伙不喜欢你对内存指手画脚,于是乎,,

抱歉!评论已关闭.