程序中需和USB设备进行通信,但中途可能会拔掉USB设备,在软件中如何检测到该动作?
如果是截获消息,该如何编程?

解决方案 »

  1.   

    可能要用到HOOK吧,这是一个用HOOK例子,希望能够给你一些思路using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;
    using System.IO;
    using System.Reflection;namespace mouseForm
    {
    /// <summary>
    /// lofinForm 的摘要说明。
    /// </summary>
    public class loginForm : System.Windows.Forms.Form
    {
    private System.Windows.Forms.TextBox textBox1;
    private System.Windows.Forms.TextBox textBox2;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.Button button2;
    public const int WH_KEYBOARD = 13;
    public const int WH_MOUSE_LL = 14;
    /// <summary>
    /// 必需的设计器变量。
    /// </summary>
    private System.ComponentModel.Container components = null; public loginForm()
    {
    //
    // Windows 窗体设计器支持所必需的
    //
    InitializeComponent(); //
    // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
    //
    } public enum HookType
    {
    WH_KEYBOARD = 2
    }
    //IntPtr
    public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam); //Declare hook handle as int.
    static int hKeyboardHook = 0; 
    HookProc KeyboardHookProcedure; /// <summary>
    /// 清理所有正在使用的资源。
    /// </summary>
    /// 

    [DllImport("kernel32")]
    public static extern int GetCurrentThreadId(); //Import for SetWindowsHookEx function.
    //Use this function to install thread-specific hook.
    [DllImport("user32.dll",CharSet=CharSet.Auto,
     CallingConvention=CallingConvention.StdCall)]
    public static extern int SetWindowsHookEx(int idHook, HookProc lpfn,
    IntPtr hInstance, int threadId); //Import for UnhookWindowsHookEx.
    //Call this function to uninstall the hook.
    [DllImport("user32.dll",CharSet=CharSet.Auto,
     CallingConvention=CallingConvention.StdCall)]
    public static extern bool UnhookWindowsHookEx(int idHook); //Import for CallNextHookEx.
    //Use this function to pass the hook information to next hook procedure in chain.
    [DllImport("user32.dll",CharSet=CharSet.Auto,
     CallingConvention=CallingConvention.StdCall)]
    public static extern int CallNextHookEx(int idHook, int nCode,
    IntPtr wParam, IntPtr lParam);
    //线程注入
    [DllImport("RunDLL.dll",CharSet=CharSet.Ansi,EntryPoint = "EnabledKey")]
    public static extern  Boolean EnabledKeys(string s); [DllImport("RunDLL.dll",CharSet=CharSet.Ansi,EntryPoint = "DisabledKey")]
    public static extern Boolean DisabledKeys(string s);
    protected override void Dispose( bool disposing )
    {
    if( disposing )
    {
    if(components != null)
    {
    components.Dispose();
    }
    }
    base.Dispose( disposing );
    }
    private int KeyboardHookProc(int nCode, IntPtr wParam, IntPtr lParam)
    {
    KeyMSG m = (KeyMSG) Marshal.PtrToStructure(lParam, typeof(KeyMSG));
    if ((int) m.vkCode == 91 || (int) m.vkCode==92 )
    //if ((int)m.vkCode==17 && (int)m.vkCode==18)
    {
    return 1;
    }
    else
    if ( (int) m.vkCode==18 || (int) m.vkCode==9 || (int) m.vkCode==115 )
    {
    return 1;
    }
    else
    if ( (int) m.vkCode==17 || (int) m.vkCode==27 )
    {
    return 1;
    }
    return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam); 
    }

    // 安装钩子
    public void HookStart()
    {
    if(hKeyboardHook == 0)
    {
    // 创建HookProc实例
    KeyboardHookProcedure = new HookProc(KeyboardHookProc); // 设置线程钩子
    hKeyboardHook = SetWindowsHookEx( WH_KEYBOARD,KeyboardHookProcedure, 
    Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]),0);
    // 如果设置钩子失败
    if(hKeyboardHook == 0 ) 
    {
    HookStop();
    throw new Exception("SetWindowsHookEx failedeeeeeeee.");
    }
    }
    } // 卸载钩子
    public void HookStop()
    {
    bool retKeyboard = true;
    if(hKeyboardHook != 0)
    {
    retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
    hKeyboardHook = 0;

    if (!(retKeyboard)) 
    {
    throw new Exception("UnhookWindowsHookEx  failedsssss.");
    }
    } public struct KeyMSG
    {
    public int vkCode;  
    public int scanCode; 
    public int flags;  
    public int time; 
    public int dwExtraInfo; 
    } #region Windows 窗体设计器生成的代码
    /// <summary>
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {
    this.textBox1 = new System.Windows.Forms.TextBox();
    this.textBox2 = new System.Windows.Forms.TextBox();
    this.label1 = new System.Windows.Forms.Label();
    this.label2 = new System.Windows.Forms.Label();
    this.button1 = new System.Windows.Forms.Button();
    this.button2 = new System.Windows.Forms.Button();
    this.SuspendLayout();
    // 
    // textBox1
    // 
    this.textBox1.Location = new System.Drawing.Point(120, 32);
    this.textBox1.Name = "textBox1";
    this.textBox1.TabIndex = 0;
    this.textBox1.Text = "";
    // 
    // textBox2
    // 
    this.textBox2.Location = new System.Drawing.Point(120, 64);
    this.textBox2.Name = "textBox2";
    this.textBox2.TabIndex = 1;
    this.textBox2.Text = "";
    // 
    // label1
    // 
    this.label1.Location = new System.Drawing.Point(64, 40);
    this.label1.Name = "label1";
    this.label1.Size = new System.Drawing.Size(48, 16);
    this.label1.TabIndex = 2;
    this.label1.Text = "用户:";
    // 
    // label2
    // 
    this.label2.Location = new System.Drawing.Point(64, 72);
    this.label2.Name = "label2";
    this.label2.Size = new System.Drawing.Size(48, 16);
    this.label2.TabIndex = 3;
    this.label2.Text = "密码:";
    // 
    // button1
    // 
    this.button1.Location = new System.Drawing.Point(64, 104);
    this.button1.Name = "button1";
    this.button1.TabIndex = 4;
    this.button1.Text = "登陆";
    this.button1.Click += new System.EventHandler(this.button1_Click);
    // 
    // button2
    // 
    this.button2.Location = new System.Drawing.Point(152, 104);
    this.button2.Name = "button2";
    this.button2.TabIndex = 5;
    this.button2.Text = "退出";
    this.button2.Click += new System.EventHandler(this.button2_Click);
    // 
    // loginForm
    // 
    this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
    this.ClientSize = new System.Drawing.Size(296, 157);
    this.Controls.Add(this.button2);
    this.Controls.Add(this.button1);
    this.Controls.Add(this.label2);
    this.Controls.Add(this.label1);
    this.Controls.Add(this.textBox2);
    this.Controls.Add(this.textBox1);
    this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
    this.Name = "loginForm";
    this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
    this.Text = "loginForm";
    this.Load += new System.EventHandler(this.loginForm_Load);
    this.ResumeLayout(false); }
    #endregion private void button2_Click(object sender, System.EventArgs e)
    {
    //DisabledKeys(System.IO.Directory.GetCurrentDirectory()+"/SASHOOK.dll");// alt+ctrl+del  需要一个  dll文件  c++builder 做的
    HookStop();
    Application.Exit();
    } private void button1_Click(object sender, System.EventArgs e)
    {
    if ( textBox1.Text=="" && textBox2.Text=="" )
    {
    DisabledKeys(System.IO.Directory.GetCurrentDirectory()+"/SASHOOK.dll");
    Application.Exit();
    }
    else
    {
    MessageBox.Show("用户没有刷卡!请刷卡后再上机!","警告",MessageBoxButtons.OK,MessageBoxIcon.Warning);
    textBox1.Text="";
    textBox2.Text="";
    return;
    }
    } private void loginForm_Load(object sender, System.EventArgs e)
    {
    //EnabledKeys(System.IO.Directory.GetCurrentDirectory()+"/SASHOOK.dll.dll" );
    HookStart();
    }
    }
    }