【问题标题】:Using win32Com (does not exist in current context)使用 win32Com(当前上下文中不存在)
【发布时间】:2013-02-24 09:06:22
【问题描述】:

我正在尝试使用 Win32 API 编写我自己的小型库以连接到串行端口。不幸的是,我发现的所有sample code 都使用 kernel32.dll(我可以这样做),但 createFile 命令使用前缀 win32Com,我假设它是我需要使用的某个命名空间的一部分。不幸的是,我无法弄清楚,作为一个菜鸟,我不知道如何确定这是我需要包含的参考资料还是其他什么。

谁能告诉我一些示例代码来解释如何做到这一点?或者告诉我哪里出错了?我将包括我的“使用”部分和 DllImport 以及我尝试在下面创建文件的位置。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO.Ports;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

这里还有一些代码,初始化表单等

[DllImport("kernel32.dll", SetLastError = true)]
        internal static extern IntPtr CreateFile(String lpFileName,
           UInt32 dwDesiredAccess, UInt32 dwShareMode,
           IntPtr lpSecurityAttributes, UInt32 dwCreationDisposition,
           UInt32 dwFlagsAndAttributes, IntPtr hTemplateFile);

但是当我使用以下内容时,我得到了错误:The name 'Win32Com' does not exist in the current context.

 hPort = Win32Com.CreateFile(cs.port,
               Win32Com.GENERIC_READ | Win32Com.GENERIC_WRITE, 0, IntPtr.Zero,
               Win32Com.OPEN_EXISTING, Win32Com.FILE_FLAG_OVERLAPPED,
               IntPtr.Zero);

我确信这是我犯的一个简单错误,但不幸的是,我目前还没有技能来找出它在哪里。

提前致谢!

【问题讨论】:

  • 只是出于好奇,为什么不能使用 System.IO.Ports.SerialPort? msdn.microsoft.com/en-us/library/…
  • 这就是我在历史上所做的,不幸的是 System.IO.Ports.SerialPort 做得很差;也就是说,它只适用于大约 75% 的硬件。 My thread heremy other one here 解释原因。非常令人沮丧,但解释了我为什么要发布这个问题:)

标签: c# dllimport createfile kernel32


【解决方案1】:

您的链接显示:“Win32Com 是一个帮助类,用作我将通过 P/Invoke 使用的 API 函数、结构和常量的静态定义的容器。”所以你需要创建它并将CreateFile 的以下声明放在那里。您还应该阅读 P/Invoke 以了解其工作原理。

【讨论】:

  • 好的,这对我来说是一个很好的起点。这些是我必须阅读六遍才能理解其中 50% 的内容,但这就是学习这些新主题的本质。谢谢,我稍后再报告。
猜你喜欢
  • 2023-03-30
  • 2019-08-05
  • 2020-07-31
  • 2021-01-16
  • 1970-01-01
  • 2018-06-07
  • 2012-10-23
  • 2021-03-25
相关资源
最近更新 更多