【发布时间】: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 here 和 my other one here 解释原因。非常令人沮丧,但解释了我为什么要发布这个问题:)
标签: c# dllimport createfile kernel32