先来一个辅助类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms; namespace HZCX.Utils
{
/// <summary>
/// 鼠标全局钩子
/// </summary>
public static class MouseHook
{
private const int WM_MOUSEMOVE = 0x200;
private const int WM_LBUTTONDOWN = 0x201;
private const int WM_RBUTTONDOWN = 0x204;
private const int WM_MBUTTONDOWN = 0x207;
private const int WM_LBUTTONUP = 0x202;
private const int WM_RBUTTONUP = 0x205;
private const int WM_MBUTTONUP = 0x208;
private const int WM_LBUTTONDBLCLK = 0x203;
private const int WM_RBUTTONDBLCLK = 0x206;
private const int WM_MBUTTONDBLCLK = 0x209; /// <summary>
/// 点
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public class POINT
{
public int x;
public int y;
} /// <summary>
/// 钩子结构体
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public class MouseHookStruct
{
public POINT pt;
public int hWnd;
public int wHitTestCode;
public int dwExtraInfo;
} public const int WH_MOUSE_LL = ; // mouse hook constant // 装置钩子的函数
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId); // 卸下钩子的函数
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook); // 下一个钩挂的函数
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam); // 全局的鼠标事件
public static event MouseEventHandler OnMouseActivity; // 钩子回调函数
public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam); // 声明鼠标钩子事件类型
private static HookProc _mouseHookProcedure;
private static int _hMouseHook = ; // 鼠标钩子句柄
/// <summary>
/// 启动全局钩子
/// </summary>
public static void Start()
{
// 安装鼠标钩子
if (_hMouseHook != )
{
Stop();
}
// 生成一个HookProc的实例.
_mouseHookProcedure = new HookProc(MouseHookProc); _hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, _mouseHookProcedure, Marshal.GetHINSTANCE(System.Reflection.Assembly.GetEntryAssembly().GetModules()[]), ); //假设装置失败停止钩子
if (_hMouseHook == )
{
Stop();
throw new Exception("SetWindowsHookEx failed.");
}
} /// <summary>
/// 停止全局钩子
/// </summary>
public static void Stop()
{
bool retMouse = true; if (_hMouseHook != )
{
retMouse = UnhookWindowsHookEx(_hMouseHook);
_hMouseHook = ;
} // 假设卸下钩子失败
if (!(retMouse))
throw new Exception("UnhookWindowsHookEx failed.");
} /// <summary>
/// 鼠标钩子回调函数
/// </summary>
private static int MouseHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
// 假设正常执行而且用户要监听鼠标的消息
if ((nCode >= ) && (OnMouseActivity != null))
{
MouseButtons button = MouseButtons.None;
int clickCount = ; switch (wParam)
{
case WM_LBUTTONDOWN:
button = MouseButtons.Left;
clickCount = ;
break;
case WM_LBUTTONUP:
button = MouseButtons.Left;
clickCount = ;
break;
case WM_LBUTTONDBLCLK:
button = MouseButtons.Left;
clickCount = ;
break;
case WM_RBUTTONDOWN:
button = MouseButtons.Right;
clickCount = ;
break;
case WM_RBUTTONUP:
button = MouseButtons.Right;
clickCount = ;
break;
case WM_RBUTTONDBLCLK:
button = MouseButtons.Right;
clickCount = ;
break;
}
if (button != MouseButtons.None && clickCount>)
{
// 从回调函数中得到鼠标的信息
MouseHookStruct MyMouseHookStruct = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));
MouseEventArgs e = new MouseEventArgs(button, clickCount, MyMouseHookStruct.pt.x, MyMouseHookStruct.pt.y, );
OnMouseActivity(null, e);
}
} // 启动下一次钩子
int inext = CallNextHookEx(_hMouseHook, nCode, wParam, lParam);
return inext;
}
}
}

Program的main函数里面调用 MouseHook.Start();

main函数里面写 Application.ApplicationExit += Application_ApplicationExit;

static void Application_ApplicationExit(object sender, EventArgs e)
{
MouseHook.Stop();
}

窗体load里面写 HZCX.Utils.MouseHook.OnMouseActivity += hook_OnMouseActivity;

窗体closing里面写 HZCX.Utils.MouseHook.OnMouseActivity -= hook_OnMouseActivity;

 void hook_OnMouseActivity(object sender, MouseEventArgs e)
{
try
{
if (this._isLoseFocusClose && e.Clicks > )
{
if (e.Button == System.Windows.Forms.MouseButtons.Left || e.Button == System.Windows.Forms.MouseButtons.Right)
{
if (!this.IsDisposed)
{
if (!this.ClientRectangle.Contains(this.PointToClient(e.Location)))
{
base.Close();
}
}
}
}
}
catch { }
}

就这样了

c# winform 窗体失去焦点关闭(钩子实现)的更多相关文章

  1. Winform 窗体获得焦点

    给窗体添加Shown事件 public void Form_Shown(object sender, EventArgs e) { this.Activate(); this.Focus(); //定 ...

  2. winform打开子窗体后,在子窗体中刷新父窗体,或者关闭子窗体刷新父窗体

    winform打开子窗体后,在子窗体中刷新父窗体,或者关闭子窗体刷新父窗体,搜集了几个方法,列举如下: 一 . 所有权法 父窗体,名称为“fuForm”,在父窗体中有个公共刷新方法,也就是窗体数据初始 ...

  3. Winform开发之窗体显示、关闭与资源释放

    Winform的窗体涉及到一般窗体(单文档窗体).MDI窗体.窗体之间的关系等,那么如果调用打开新窗体.如何关闭窗体.窗体资源的释放等都关系到软件运行的效率,本文一一介绍 1.窗体的显示 从一个窗体打 ...

  4. Winform 窗体的操作

    原文:http://www.cnblogs.com/Billy-rao/archive/2012/05/16/2503437.html 怎样能使winform窗体的大小固定住,不能调整其大小 窗体Fo ...

  5. WinForm窗体嵌入

    一.在winform窗体上添加两个控件 1.容器>Panel 2.添加 SideBar.dll (下载链接:http://pan.baidu.com/s/1o6qhf9w) (1)将SideBa ...

  6. C#中WinForm窗体事件的执行次序

    C#中WinForm窗体事件的执行次序如下: 当 Windows Form 应用程序启动时,会以下列顺序引发主要表单的启动事件:        System.Windows.Forms.Control ...

  7. C# winform窗体设计-通过条件查询数据

    在winform 数据库设计中,有时候需要通过条件查询对应的数据,并且将数据显示在文本框(or 富文本框)中,下面,小编将讲述通过一个条件: 首先,我们需要对数据库建立连接,并且执行数据库命令,在此之 ...

  8. Winform窗体事件发生顺序

    Form 和Control 类公开了一组与应用程序启动和关闭相关联的事件.当Windows 窗体应用程序启动时,主窗体的启动事件按以下顺序引发: System.Windows.Forms.Contro ...

  9. 小例子(二)、winform窗体间的关系

    写一个关于winform窗体间的关系 1.登陆,思路:登陆后隐藏登陆窗体,关闭Form2时结束整个应用程序. //登陆窗体 private void button2_Click(object send ...

随机推荐

  1. 【使用篇二】SpringBoot定时任务Scheduled(14)

    在日常项目运行中,我们总会有需求在某一时间段周期性的执行某个动作.比如每天在某个时间段导出报表,或者每隔多久统计一次现在在线的用户量.在springboot中可以有很多方案去帮我们完成定时器的工作,有 ...

  2. 【安富莱】V6,V5开发板用户手册,重在BSP驱动包设计方法,HAL库的框架学习,授人以渔(2019-11-04)

    说明: 1.本教程重在BSP驱动包设计方法和HAL库的框架学习,并将HAL库里面的各种弯弯绕捋顺,从而方便我们的程序设计. 2.本次工程延续以往的代码风格,从底层BSP驱动包到应用代码,变量命名,文件 ...

  3. libwebrtc & libmediasoupclient编译

    本文简单介绍在Ubuntu下libwebrtc的编译过程. 由于网速限制,实际编译过程是在远程vps上编译滴. 系统环境 Ubuntu 18.04系统的虚拟主机. root@vultr:~# pwd ...

  4. ETCD:与etcd进行交互

    原文地址:Interacting with etcd 与etcd进行交互 用户更多的是通过putting或者是getting从etcd获取一个键对应的值.这一部分描述了如何通过etcdctl做这些工作 ...

  5. Java题库——Chapter4 循环

    1)How many times will the following code print "Welcome to Java"? int count = 0; while (co ...

  6. MySQL插入数据时报错Cause: java.sql.SQLException: #HY000的解决方法

    数据库中有字段要求不能为空,但是insert插入的时候,改字段没有值

  7. Winform中怎样在工具类中对窗体中多个控件进行操作(赋值)

    场景 需求是在窗体加载完成后掉用工具类的方法,工具类中获取窗体的多个控件对象进行赋值. 注: 博客主页: https://blog.csdn.net/badao_liumang_qizhi 关注公众号 ...

  8. ASP.NET Core 2.2 WebApi 系列【四】集成Swagger

    Swagger 是一款自动生成在线接口文档+功能测试功能软件 一.安装程序包 通过管理 NuGet 程序包安装,搜索Swashbuckle.AspNetCore 二.配置 Swagger 将 Swag ...

  9. centos添加用户并赋予管理员权限

    用centos时,root用户一般都是超级管理员使用的,一般不轻易给别人,但是有时候同事安装软件时需要root账号,又不得不给,只能重新建一个用户,并赋予管理员权限.下面介绍创建用户并赋予管理员权限的 ...

  10. JPA入门简介与搭建HelloWorld(附代码下载)

    场景 在学习JPA之前先来了解下JDBC与各大数据库的关系. 很久之前出现了很多数据库比如Mysql.Oracle.SqlServer.DB2等.这就导致了应用程序要连哪个数据库就要使用哪个数据库的A ...