In .NET, strings are immutable: When you pass them out to an API, you cant modify them. However, VB.NET applies the VBByRefStr unmanaged type-marshaling attribute to the string. This allows VB.NET to create a temporary buffer, copy that back to a new string, then point the original string to the new string:
Public Declare Function GetWindowText _
Lib "User32.Dll" _
(ByVal hwnd As Int32, _
ByVal lpString As String, _
ByVal cch As Int32) As Int32
To use this declaration, simply initialize the string to the right size:
Dim s As String = Space(256)
Dim rtn as Int32 = GetWindowText(hwnd, s, 256)
The API declaration is equivalent to:
Public Declare Function GetWindowText _
Lib "User32.Dll" (ByVal hwnd As Int32, _
<System.Runtime.InteropServices.MarshalAs( _
Runtime.InteropServices.UnmanagedType.VBByRefStr)> _
ByRef lpString As String, _
ByVal cch As Int32) As Int32
It's quick, easy and you get access to all the articles on DevX.
This registration/login is to allow you to read articles on devx.com. Already a member?
To become a member of DevX.com create your Member Profile by completing the form below. Membership is free!
If you have a hot tip and we publish it, we'll pay you. However, due to accounting overhead we no longer pay $10 for a single tip submission. You must accumulate 10 acceptable tips to receive payment. Be sure to include a clear explanation of what the technique does and why it's useful. If it includes code, limit it to 20 lines if possible. Submit your tip here.