我应该如何在VB.NET中导入DLL?一个例子是:
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function GetWindowText(ByVal hwnd As IntPtr, ByVal lpString As StringBuilder, ByVal cch As Integer) As Integer
End Function
如果我把它放在Class或其他地方,我会得到“DLLimport未定义”我正在使用Visual Studio 2008 Professional
答案 0 :(得分:35)
您必须将Imports System.Runtime.InteropServices
添加到源文件的顶部。
或者,您可以完全限定属性名称:
<System.Runtime.InteropService.DllImport("user32.dll", _
SetLastError:=True, CharSet:=CharSet.Auto)> _
答案 1 :(得分:6)
Imports System.Runtime.InteropServices
答案 2 :(得分:5)
我在pinvoke.net上的 getwindowtext (user32) 中看到,您可以放置一个MarshalAs
语句来声明StringBuffer等效于LPSTR。
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Ansi)> _
Public Function GetWindowText(hwnd As IntPtr, <MarshalAs(UnManagedType.LPStr)>lpString As System.Text.StringBuilder, cch As Integer) As Integer
End Function
答案 3 :(得分:2)
你也可以尝试这个
Private Declare Function GetWindowText Lib "user32.dll" (ByVal hwnd As IntPtr, ByVal lpString As StringBuilder, ByVal cch As Integer) As Integer
我总是使用声明功能而不是 DllImport ... 它更简单,更短,并且相同
答案 4 :(得分:2)
我知道这已经得到了解答,但是这里有一个例子,供尝试在vb项目中使用SQL Server类型的人使用:
public void Main()
{
string path = @"drive"; // TODO
ApplyAllFiles(path, ProcessFile);
}
public void ProcessFile(string path)
{
/* ... */
}
public void ApplyAllFiles(string folder, Action<string> fileAction)
{
System.Collections.ArrayList FileList = new System.Collections.ArrayList();
List<string> logger = new List<string>();
DateTime DateFilter = DateTime.Now.AddMonths(-6);
foreach (string file in Directory.GetDirectories(folder))
{
fileAction(file);
}
foreach (string subDir in Directory.GetDirectories(folder))
{
string rootfolder = "root folder";
if (subDir.Contains(rootfolder))
{
FileList.Add(subDir);
Dts.Variables["User::objDirectoryList"].Value = FileList;
//MessageBox.Show(subDir);
}
try
{
ApplyAllFiles(subDir, fileAction);
}
catch (UnauthorizedAccessException e)
{
logger.Add(e.Message);
}
catch (System.IO.DirectoryNotFoundException e)
{
logger.Add(e.Message);
}
}
}