[VB.NET]委托调用---invoke

在VB6平台是没有多线程这一说的,而VB.NET有了这个概念,这样对于同步模块化操作是很方面的.

可是同样也存在着问题.跨线程操作COM有时候会异常.

托管程序~~~每一个线程都有上下文,主线程(或者说创建控件的线程)操作COM控件是没问题的.

但是其他线程就不行了,可能会引发异常.

但是有一个叫"托管调用"的函数---invoke,使得跨线程操作是安全的.

 

比如说一个控件在FORM里,一个线程(非主线程)去操作这个控件,就需要invoke调用FORM的函数再去操作(自写函数),这样就安全了.

 

MSDN上是这样写的,看的我迷迷糊糊

 

**一个签名版的二次开发,遇到下面问题** WindowsApplication1.Module1+SubClassProcDelegate::Invoke”类型的已垃圾回收委托进行了回调。这可能会导致应用程序崩溃、损坏和数据丢失。向非托管代码传递委托时,托管应用程序必须让这些委托保持活动状态,直到确信不会再次调用它们。 ``` Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Module1.SubclassWindow(Me.Handle) End Sub ``` Module Module1 Public Const HD_OK As Integer = 31111 Public Const HD_CANCEL As Integer = 31112 Public Const HD_REALTIMEDATA As Integer = 31113 Public inkingWindowWidth As Integer Public inkingWindowHeight As Integer Private Const GWL_WNDPROC = (-4) Private procOld As Integer Private Declare Function CallWindowProc Lib "USER32.DLL" Alias "CallWindowProcA" (ByVal lpPrevWndFunc As Integer, ByVal hWnd As Integer, ByVal uMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer Public Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Integer, ByVal nIndex As Integer, ByVal dwNewLong As SubClassProcDelegate) As Integer '重载API函数,最后一个参数为委托类型,注意Long类型参数变成了Integer. Delegate Function SubClassProcDelegate(ByVal hwnd As Integer, ByVal msg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer '定义窗口过程的委托类型 Public Sub SubclassWindow(ByVal hWnd As Integer) procOld = SetWindowLong(hWnd, GWL_WNDPROC, AddressOf SubWndProc) End Sub Public Function SubWndProc(ByVal hWnd As Integer, ByVal iMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer If hWnd = Form1.Handle.ToInt32 Then Dim X, Y, Pressure, IsPenDown As Integer X = wParam And 65535 Y = (wParam / 65536) And 65535 X = (X / 65535 * inkingWindowWidth) And 65535 Y = (Y / 65535 * inkingWindowHeight) And 65535 Pressure = lParam And 65535 IsPenDown = (lParam / 65536) And 65535 SubWndProc = True Exit Function End If SubWndProc = CallWindowProc(procOld, hWnd, iMsg, wParam, lParam) End Function End Module
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页