当前位置:编程学习 > C#/ASP.NET >>

DeviceIoControl 求救

我不知道那裹出错,都有连上设备,但就是没辨法控制
请帮我看看那出了错。


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

namespace GPIO
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool DeviceIoControl(
          SafeFileHandle hDevice,
          uint dwIoControlCode,
          ref uint InBuffer,
          int nInBufferSize,
          byte[] OutBuffer,
          UInt32 nOutBufferSize,
          ref UInt32 out_count,
          IntPtr lpOverlapped);


        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern  SafeFileHandle CreateFile(
          string FileName,
          ulong DesiredAccess,
          uint ShareMode,
          IntPtr SecurityAttributes,
          uint CreationDisposition,
          uint FlagsAndAttributes,
          IntPtr hTemplateFile
          );


        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CloseHandle(SafeFileHandle hObject);


        public const int FILE_ATTRIBUTE_NORMAL = 0x00000080;
        public const UInt64 GENERIC_READ = 0x80000000;
        public const uint OPEN_EXISTING = 3;
        public const UInt32 INVALID_HANDLE_VALUE = 0xffffffff;
        public const UInt64 GENERIC_WRITE = 0x40000000L;
        public const uint FILE_FLAG_OVERLAPPED = 0x40000000;
        private const uint FILE_DEVICE_UNKNOWN = 0x00000022;
        private const uint FILE_ATTRIBUTE_SYSTEM = 0x00000004;


        private const uint USB2SER_IOCTL_INDEX = 0x0800;
        private const uint METHOD_BUFFERED = 0;
        private const uint FILE_ANY_ACCESS = 0;

        protected SafeFileHandle hCOM;

        private static uint GP0_SET_VALUE = CTL_CODE(FILE_DEVICE_UNKNOWN, USB2SER_IOCTL_INDEX + 22, METHOD_BUFFERED, FILE_ANY_ACCESS);

        static uint CTL_CODE(uint DeviceType, uint Function, uint Method, uint Access)
        {
            return ((DeviceType << 16) | (Access << 14) | (Function << 2) | Method);
        }


        private void button1_Click(object sender, EventArgs e)
        {
            //serialPort1.StopBits = System.IO.Ports.StopBits.One;
            //serialPort1.PortName = cmbCOM.Text;
            //serialPort1.BaudRate = 115200;
            //serialPort1.Open();
            //IntPtr hCOM;

            string tmpStr = "\\\\.\\" + cmbCOM.Text;

            hCOM = CreateFile(tmpStr, GENERIC_READ | GENERIC_WRITE,
                0, IntPtr.Zero, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, (IntPtr)null);

            string strResponse = "OPEN " + cmbCOM.Text + " port ";
            if (hCOM.Equals( (IntPtr)INVALID_HANDLE_VALUE))
                strResponse += "FAILED.";
            else
            {
                strResponse += "Successfully!";
                //m_hCOM = hCOM;
                //m_hCOM = FindWindow(null, "Form1");
                //m_comStr = comStr;
            }
            textBox1.Text = strResponse;
            //AddResponseString(strResponse);

            //if (!m_hCOM.Equals(INVALID_HANDLE_VALUE))
            //    OnBnClickedBtnSetstatus();

           // OpenSymbolicPort();

        }
      

        private void button2_Click(object sender, EventArgs e)
        {
            // 關閉232
            serialPort1.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
           
            uint val;


            val = (uint)(int.Parse(textBox2.Text));
            bool bSuccess = PL2303_GP0_SetValue(hCOM, val);

            if (bSuccess)
                textBox1.Text += "SET GP0 value Successfully!";

            if (!bSuccess)
            {
                CloseHandle(hCOM);
                textBox1.Text += "SET GP0 value FAILED.";
            }




            textBox1.Text += val.ToString();
        }

        private bool PL2303_GP0_SetValue(SafeFileHandle hDrv, uint val)
        {
            UInt32 nBytes=0;
            
            byte[] addr = new byte[6];


            bool bSuccess = DeviceIoControl(hDrv, GP0_SET_VALUE, ref val, sizeof(uint), null, 0, ref nBytes, IntPtr.Zero);
           
            return bSuccess;
        }

      
    }
}




--------------------编程问答-------------------- 不知道你解決了沒,我改您的程式,並用 Netport-8800 測試過可以用了
NetPort-8800 只有用 GP1 去控制開關

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

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public const int FILE_ATTRIBUTE_NORMAL = 0x00000080;
        public const uint GENERIC_READ = 0x80000000;
        public const uint GENERIC_WRITE = 0x40000000;
        public const int OPEN_EXISTING = 3;
        // public const UInt32 INVALID_HANDLE_VALUE = 0xffffffff;

        private const uint FILE_FLAG_OVERLAPPED = 0x40000000;
        private const uint FILE_DEVICE_UNKNOWN = 0x00000022;
        private const uint FILE_ATTRIBUTE_SYSTEM = 0x00000004;
        private const uint USB2SER_IOCTL_INDEX = 0x0800;
        private const uint METHOD_BUFFERED = 0;
        private const uint FILE_ANY_ACCESS = 0;





        public Form1()
        {
            InitializeComponent();
        }

        IntPtr pl2303 = (IntPtr)(-1);

        static uint CTL_CODE(uint DeviceType, uint Function, uint Method, uint Access)
        {
            return ((DeviceType << 16) | (Access << 14) | (Function << 2) | Method);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (pl2303 == (IntPtr)(-1))
            {
                pl2303 = CreateFile("COM8",
                                    GENERIC_READ | GENERIC_WRITE,
                                    0,
                                    IntPtr.Zero,
                                    OPEN_EXISTING,
                                    FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
                                    IntPtr.Zero);
            }
            else
                MessageBox.Show("Port already open");
            if (pl2303 == (IntPtr)(-1))
            {
                MessageBox.Show("open error");
            }
            else
            {
                MessageBox.Show("open success");
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (pl2303 != (IntPtr)(-1))
            { // pl2303 open success
                byte val = 0;
                if (PL2303_GP1_GetValue(pl2303, ref  val))
                {
                    button2.Text = val.ToString();
                    if (val == 0)
                    {
                        if (PL2303_GP1_Enable(pl2303))
                        {
                            if (PL2303_GP1_SetValue(pl2303, 1))
                            {
                                MessageBox.Show("open");
                            }
                        }
                        else
                        {
                            MessageBox.Show("enable fail");
                        }
                    }
                    else
                    {
                        if (PL2303_GP1_Enable(pl2303))
                        {
                            if (PL2303_GP1_SetValue(pl2303, 0))
                            {
                                MessageBox.Show("close");
                            }
                        }
                        else
                        {
                            MessageBox.Show("enable fail");
                        }
                    }

                }
            }
        }
        private bool PL2303_GP1_SetValue(IntPtr hDrv, byte val)
        {
            uint nBytes = 0;
            byte dummybyte = 0;
            uint GP1_SET_VALUE = CTL_CODE(FILE_DEVICE_UNKNOWN, USB2SER_IOCTL_INDEX + 23, METHOD_BUFFERED, FILE_ANY_ACCESS);
            bool bSuccess = DeviceIoControl(hDrv, GP1_SET_VALUE, ref val, sizeof(byte), ref dummybyte,
                            0,
                            ref nBytes,
                            IntPtr.Zero);

            // BOOL bSuccess = DeviceIoControl(hDrv, GP1_SET_VALUE,&val, sizeof(BYTE), NULL, 0, &nBytes, NULL);

            MessageBox.Show(val.ToString());
            return bSuccess;
        }

        private bool PL2303_GP1_GetValue(IntPtr hDrv, ref byte val)
        {
            uint nBytes = 0;
            byte dummybyte = 0;
            uint GP1_GET_VALUE = CTL_CODE(FILE_DEVICE_UNKNOWN, USB2SER_IOCTL_INDEX + 25, METHOD_BUFFERED, FILE_ANY_ACCESS);


            bool bSuccess = DeviceIoControl(hDrv, GP1_GET_VALUE, ref dummybyte, 0, ref val,
                            sizeof(byte),
                            ref nBytes,
                            IntPtr.Zero);

            // BOOL bSuccess = DeviceIoControl(hDrv, GP1_GET_VALUE,NULL, 0, val, sizeof(BYTE), &nBytes, NULL);

            MessageBox.Show(val.ToString());
            return bSuccess;
        }

        private bool PL2303_GP1_Enable(IntPtr hDrv)
        {
            uint nBytes = 0;
            byte enable = 1;
            byte dummybyte = 0;
            uint GP1_OUTPUT_ENABLE = CTL_CODE(FILE_DEVICE_UNKNOWN, USB2SER_IOCTL_INDEX + 21, METHOD_BUFFERED, FILE_ANY_ACCESS);

            bool bSuccess = DeviceIoControl(hDrv, GP1_OUTPUT_ENABLE, ref enable, sizeof(byte), ref dummybyte,
                            0,
                            ref nBytes,
                            IntPtr.Zero);

            // BOOL bSuccess = DeviceIoControl(hDrv, GP1_OUTPUT_ENABLE, &enable, sizeof(BYTE), NULL, 0, &nBytes, NULL);


            return bSuccess;
        }

        [DllImport("kernel32.dll")]
        private static extern IntPtr CreateFile(
        string lpFileName,
        uint dwDesiredAccess,
        int dwShareMode,
        IntPtr lpSecurityAttributes,
        int dwCreationDisposition,
        uint dwFlagsAndAttributes,
        IntPtr hTemplateFile
         );

        [DllImport("kernel32.dll", EntryPoint = "DeviceIoControl", SetLastError = true)]
        internal static extern bool DeviceIoControl(
            IntPtr hDevice,
            uint dwIoControlCode,
            ref byte lpInBuffer,
            uint nInBufferSize,
            ref byte lpOutBuffer,
            int nOutBufferSize,
            ref uint lpBytesReturned,
            IntPtr lpOverlapped);


    }
}
供您參考
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,