日期:2014-05-18  浏览次数:20746 次

在VS2005的C# Winform程序里安装“全局钩子”失败的问题
这个程序是别人给我的,我用VS2005运行报错,提示 
“安装失败!SetWindowsHookEx failed.” 
据说是VS2005安全机制的问题,谁能帮我解决问题
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;

namespace HookProj
{
/// <summary>
/// KeyboardHookForm 的摘要说明。
/// </summary>
public class KeyboardHookForm : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.TextBox textBox1;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;


public KeyboardHookForm()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();

//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}

/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
// 
// button1
// 
this.button1.Location = new System.Drawing.Point(24, 8);
this.button1.Name = "button1";
this.button1.TabIndex = 0;
this.button1.Text = "安装";
this.button1.Click += new System.EventHandler(this.button1_Click);
// 
// button2
// 
this.button2.Enabled = false;
this.button2.Location = new System.Drawing.Point(192, 8);
this.button2.Name = "button2";
this.button2.TabIndex = 1;
this.button2.Text = "卸载";
this.button2.Click += new System.EventHandler(this.button2_Click);
// 
// textBox1
// 
this.textBox1.Location = new System.Drawing.Point(16, 40);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textBox1.Size = new System.Drawing.Size(264, 112);
this.textBox1.TabIndex = 2;
this.textBox1.Text = "";
// 
// KeyboardHookForm
// 
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(292, 166);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Name = "KeyboardHookForm";
this.Text = "键盘钩子";
this.Closing += new System.ComponentModel.CancelEventHandler(this.KeyboardHookForm_Closing);
this.ResumeLayout(false);

}
#endregion

private void button1_Click(object sender, System.EventArgs e)
{
try
{
HookStart();
MessageBox.Show("安装成功");
this.button1.Enabled=false;
this.button2.Enabled=true;
}
catch(Exception ex)
{
MessageBox.Show("安装失败!"+ex.Message);
}
}

private void button2_Click(object sender, System.EventArgs e)
{
try
{
HookSto