const int GENERIC_READ = 0x80000000;
const int GENERIC_WRITE = 0x40000000;
 
const int OPEN_EXISTING = 3;[DllImport("kernel32.dll")
public static extern IntPtr CreateFileA(string lpFileName, int dwDesiredAccess, int dwShareMode, int lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile);
private void Button1_Click(Object sender, EventArgs e)
{
  IntPtr iHandle = CreateFileA("LPT1", GENERIC_READ|GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
  if(iHandle.ToInt32() == -1)
  {
    MessageBox.Show("can not open port");
  }
  else
  {
    MessageBox.Show("Open Success!");
    FileStream fs = new FileStream(iHandle, FileAccess.ReadWrite);
    StreamReader sr = new StreamReader(fs);
    StreamWriter sw = new StreamWriter(fs);
  }
}

解决方案 »

  1.   

    http://www.ellkay.com/ConvertVB2CSharp.htm
      

  2.   

    const GENERIC_READ = &H80000000;
        const GENERIC_WRITE = &H40000000;
     
        const OPEN_EXISTING = 3;
     
     public [DllImport("GAIS", SetLastError=true)] static extern IntPtr CreateFile Lib "kernel32" Alias "CreateFileA" ( string  lpFileName,  int dwDesiredAccess,  int dwShareMode,  int lpSecurityAttributes,  int dwCreationDisposition,  int dwFlagsAndAttributes,  int hTemplateFile) {
     
    private void Button1_Click( System.object sender,  System.EventArgs e)  Button1.Click {
             IntPtr iHandle;
            iHandle = CreateFile("LPT1", GENERIC_READ || GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
            if ((iHandle.ToInt32 = -1) ) {
                MsgBox("can not open port");
            } else {
                MsgBox("Open Succes!");
                FileStream  fs = new FileStream(iHandle, FileAccess.ReadWrite);
                StreamReader  sr = new StreamReader(fs) //读数据;
                StreamWriter  sw = new StreamWriter(fs) //些数据;
            }
        }
      

  3.   

    我试了一下,好像不行,在DllImport中出错,请问要把他放在什么位置?
      

  4.   

    用doose() ( ) 信誉:96 的法子试试,那是个专门的工具:)