TheArticleIt includes the processing method for converting the API functions referenced by addressof operator in VB to VB. NET and the method for entrusting garbage collection.
VB:
The API function setwindowlong is defined as follows in VB:
Private declare function setwindowlong & lib "USER32" alias "setwindowlonga" (byval hwnd &, byval nindex &, byval dwnewlong &)
The reference format is as follows:
Procold = setwindowlong (Me. hwnd, gwl_wndproc,AddressofWindowproc)
Addressof is the address for obtaining the windowproc function.
VB. NET:
When you transfer to VB. NET, if you still declare setwindowlong as the following form:
Private declare function setwindowlong lib "user32.dll" alias "setwindowlonga" (byval hwnd as integer, byval nindex as integer, byval dwnewlong as integer) as integer
Procold = setwindowlong (Me. hwnd, gwl_wndproc,AddressofWindowproc), an error occurs. The "addressof" expression cannot be converted to "integer" because "integer" is not the delegate type.
In this case, the application declares setwindowlong as the following form,
Private declare function setwindowlong lib "user32.dll" alias "setwindowlonga" (byval hwnd as integer, byval nindex as integer, byval dwnewlongDelegatewindowproc) As integer
WhereDelegatewindowprcoFor the delegate of the function to return the address,For example, the function prototype private function windowproc (byval hwnd as integer, byval imsg as integer, byval wparam as integer, byval lparam as integer) as integer, it is declared that the delegate is private delegate function delegatewindowproc (byval hwnd as integer, byval imsg as integer, byval wparam as integer, byval lparam as integer) as integer
The reference takes the following form:
Dim mysub as new delegatewindowproc (addressof windowproc)
Procold = setwindowlong (m_hwnd, gwl_wndproc, mysub)
In this way, when you run for a period of time, the error "delegate to be garbage collected" will occur, resulting inProgramThere are two ways to solve this problem:
Method 1:
Dim mysub as new delegatewindowproc (addressof windowproc)
Procold = setwindowlong (m_hwnd, gwl_wndproc, mysub)
Gchandle. alloc (mysub) ''creates a handle for the delegate to avoid garbage collection and error
The second method to avoid garbage collection:
Dim mysub as new delegatewindowproc (addressof windowproc)
GC. Collect ()
GC. waitforpendingfinalizers ()
Procold = setwindowlong (m_hwnd, gwl_wndproc, mysub)