gpt4 book ai didi

vb.net - C# DLLImport 转换为 VB.NET DLLImport ......我错过了什么?

转载 作者:行者123 更新时间:2023-12-01 07:42:24 26 4
gpt4 key购买 nike

在 C# 中,我有这个:

[DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]
public static extern IntPtr GetDesktopWindow();

因此,我尝试转换为 VB.NET:
<DllImport("user32.dll", EntryPoint:="GetDesktopWindow")>
Function GetDesktopWindow() As IntPtr
End Function

但我收到一个错误...
“导入 System.Runtime.InteropServices.DllImportAttribute 不能应用于实例方法。”

有人可以解释我需要做什么来解决这个问题,甚至更好的是,告诉我为什么?

谢谢!

最佳答案

您忘记转换 static从 C# 声明到 VB.NET 的关键字。这就是错误消息告诉您的内容。除非你有一个静态方法,否则你是在声明一个实例方法,并且 DllImportAttribute不能应用于实例方法。
static 的 VB.NET 等价物是 Shared .所以你的声明应该是这样的:

<DllImport("user32.dll", EntryPoint:="GetDesktopWindow")>
Shared Function GetDesktopWindow() As IntPtr
End Function

我觉得有必要指出其他一些事情:
  • 没有必要指定 EntryPoint当您的函数声明具有相同的名称时。并不是说这样做会造成任何伤害,但我觉得如果你省略它,它可以减少重复并减少出错的机会。
  • 像这样的 P/Invoke 声明通常应该进入一个名称类似于 NativeMethods 的静态类。 (StyleCop 强制执行此准则)。在 VB.NET 中,静态类称为模块。所以它看起来像这样:
    Module NativeMethods
    <DllImport("user32.dll")>
    Shared Function GetDesktopWindow() As IntPtr
    End Function
    End Module
  • 在旧版本的 VB(VB 10 之前,随 VS 2010 一起提供)中,您需要换行符才能将函数声明分成多行。那些丑陋的疣使它看起来像这样:
    Module NativeMethods
    <DllImport("user32.dll")> _
    Shared Function GetDesktopWindow() As IntPtr
    End Function
    End Module

  • 最后, 小心使用桌面窗口GetDesktopWindow 返回功能! Lots of people abuse it ,并且大多数时候,当我看到人们试图检索它的句柄时,这表明他们已经做错了。 (不是说你是,因为我看不到你的其余代码,只是需要注意的事情!)

    关于vb.net - C# DLLImport 转换为 VB.NET DLLImport ......我错过了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11622356/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com