Question

I'm trying to use the Win32 API to write my own small library for connecting to a serial port. Unfortunately all the sample code that I find uses the kernel32.dll (which I can do) but the createFile command uses the prefix win32Com, which I am assuming is part of some namespace which I need to use. Unfortunately I can't figure it out, and being a noob I don't know how to find out if this is a reference I need to include, or something else.

Can anyone point me to some sample code that explains how to do this? Or tell me where I am going wrong? I will include my 'usings' section and the DllImport as well as where I am trying to create a file below.

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;

There is some more code here, initializing the form, etc.

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

But when I use the following, I get the error: 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);

I'm sure this is a simple mistake I am making but unfortunately I don't have the skillset at this point to find out where it is.

Thanks in advance!

Was it helpful?

Solution

Your link says: "Win32Com is a helper class used as a container for static definitions of the API functions, structures, and constants that I will be using via P/Invoke." so you need to create it and put the following declaration of CreateFile there. You should also read about P/Invoke to understand how does this work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top