Winform中在Form上截取消息的两种方法比较

c# winform 鼠标、键盘消息拦截 vs2013 c# winform ,PreFilterMessage拦截本程序内的鼠标消息,获取鼠标与键盘钩子获取鼠标与键盘消息,或者取消键盘消息 立即下载

比较常用的是重载Form的DefWndProc方法,例如截取鼠标按下的消息:

protected   override   void  DefWndProc( ref  Message m)
        
{
            
if ( m.Msg ==  0x0201 )
            
{
                MessageBox.Show(m.Msg.ToString());
            }

            
else
            
{
                
base.DefWndProc (ref m);
            }

        }

还可以通过另一种办法,使用IMessageFilter 接口:

public   class  MessageFilter : IMessageFilter 
    {
                
public   bool  PreFilterMessage( ref  Message m) 
               {
                        
if  (m.Msg  ==   0x0201 ) 
                       {
                                MessageBox.Show(
" WM_LBUTTONDOWN is:  "   +  m.Msg);
                              
return   true ;
                       }
                      
return   false ;
        }

    }

然后使用Application.AddMessageFilter方法,例如:
private static MessageFilter msgFliter = new MessageFilter();
在Main方法中注册消息筛选器:
Application.AddMessageFilter(msgFliter);
如果要取消注册,可以调用Application.RemoveMessageFilter方法

 

实际上我们简单的区分这两者的不同:

 

DefWndProc : (From MSDN)

通常,仅在截获窗口消息并需要默认窗口过程来处理该消息时,才调用 DefWndProc 方法。不应调用 DefWndProc 将窗口消息发送到窗口,而应调用 Win32 SendMessage 函数。

Handle 属性为 0 时,调用 DefWndProc 是错误的。

给继承者的说明 在派生类中重写此方法可实现特定本机窗口或 .NET Windows 窗体 Control 的通用自定义消息处理。可以在调用此方法的基类实现(执行标准消息处理)之前或之后执行自定义处理,也可以使用自定义处理而不调用此方法的基类实现。 为应用程序添加自定义消息处理则可以通过 Application 类的 AddMessageFilter 方法来实现。

 

Application.AddMessageFilter() : (From MSDN)

使用消息筛选器来防止引发特定事件,或在将某事件传递给事件处理程序之前使用消息筛选器对其执行特殊操作。消息筛选器对特定线程是唯一的。

若要防止调度某消息,传递给该方法的 value 参数实例必须用处理该消息的代码重写 PreFilterMessage 方法。该方法必须返回 false。

 

简单的说明下:

两者的功能实际上是不一样的:

有一个简单的例子来说明:

 我们新建一个Form,添加两种方法的消息处理Wm_Lbutton=0x021;另外在Form上添加一个Button,响应函数是MessageBox.Show();

代码如下:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            MessageDo();
        }
        private const int WM_Lbutton = 0x201;  
        protected override void DefWndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_Lbutton:
                    {
                        MessageBox.Show(" DefWndProc ");
                    }
                    break;
                case WM_ShowString:
                    {
                        MessageBox.Show("Show Stinrg Message have happened and Params are "+m.WParam.ToString()+":"+m.LParam.ToString());
                    }
                    break;
                default:
                    base.DefWndProc(ref m);
                    break;
            }
           
            //base.DefWndProc(ref m);
        }      
        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Button 1 was clicked just now !");
        }    
        private MessageFilter myfilter = new MessageFilter();
        private void MessageDo()
        {
            Application.AddMessageFilter(myfilter);
        }   
     
    }
    public class MessageFilter:IMessageFilter
    {
        public bool PreFilterMessage(ref Message m)
        {
            if (m.Msg == 0x201)
            {
                MessageBox.Show(" PreFilter ");
                return true;
            }
            return false;

        }
    }

运行后的结果是这样的:

 一直显示的  MessageBox() : PrefilTer,就算是Button按键也不能响应,整个UI的LButton都被他过滤了。

如果删除MessageFilter,结果就是: 当LButton发生的时候,只要不是在Button上面,就会MessageBox():DefWndProc

 

这个例子就可以看出最大的不同。

明天把这个东西补充下,有时间查查资料。

Flutter 中使用蓝牙插件报错,说没有权限怎么解决 2、在build.grale里面更改一下版本号,我修改的是targetSdkVersion这个版本号,需要根据你自己的版本进行更改,记得更改之后先flutter clean一下再run。搞了一晚上,没搞出来,第二天用同事手机测试发现他手机可以,我手机还是不行,才发现是Android版本问题,需要修改两处地方。废话不多说,咱先看报错信息。 阅读详情

相关推荐

图像配准方法之灰度信息法

这系列文章是5年前的,也是从自己的QQ(632846506)日志中移过来的。https://user.qzone.qq.com/632846506/infocenter。      图像配准的方法主要有三种:基于灰度信息方法;基于空间变换域方法;基于图像特征的方法。 一、灰度信息法。     灰度信息法直接利用两幅图像之间灰度度量的相似性,以图像内部的信息为依据,采用搜索方法寻找相似度最大或

月秀明竹的专栏 1万+

使用ImessageFilter接口实现截获键盘或者鼠标的消息

在C#中可以使用IMessageFilter 接口来截获应用程序的消息I MessageFilter 接口允许应用程序在消息被调度到控件或窗体之前捕获它。可以将实现 IMessageFilter 接口的类添加到应用程序的消息泵中,以在消息被调度到控件或窗体之前将它筛选出来或执行其他操作。若要将消息筛选器添加到应用程序的消息泵中,请使用 Application 类中的AddMessageFilter...

hududanyzd 544

STM32驱动WS2812B实现音乐频谱可视化系统

本文详细介绍了基于STM32驱动WS2812B灯带实现音乐频谱可视化系统的设计与实现。通过FFT算法实时分析音频信号,将频谱映射到炫彩灯光控制系统,结合PWM和DMA技术实现低延迟响应。系统支持多模式切换和动态亮度调节,适用于创意灯光秀和智能家居场景。

weixin_29171129的博客 302

C#通过IMessageFilter捕获鼠标消息(转载)

在c#中怎样禁用鼠标左键的使用,其实我们可以通过ImessageFilter接口下的PreFilterMessage方法、Application类的AddMessageFilter方法,RemoveMessageFilter方法和Message结构的Msg属性来禁用鼠标左键。Message结构包装Windows发送的消息,可使用该结构包装消息,并将其分配给窗口过程以进行调度,还可以使用该结构获取系...

weixin_30700099的博客 500

保姆级教程:用Python+OpenCV实现相移法与格雷码三维重建(从生成条纹到点云生成)

本文详细介绍了使用Python和OpenCV实现相移法与格雷码三维重建的全流程,从条纹生成到点云计算。通过结构光技术,结合相移法和格雷码,实现高精度的三维重建,适用于无纹理物体表面的密集对应点生成。教程包含环境搭建、条纹生成、相位计算、三维点云重建及常见问题排查,适合计算机视觉开发者和研究人员。

weixin_33443333的博客 350

Windows 11“此应用已被管理员阻止运行”解决方案

通过本文介绍的两种方法,你应该能够解决Windows 11中“此应用已被管理员阻止运行”的问题。无论你选择创建新管理员账户还是禁用管理员批准模式,都请确保了解相关操作的风险,并根据你的实际需求做出选择。通过禁用“用户账户控制:以管理员批准模式运行所有管理员”设置,可以解决因系统安全设置导致的应用程序被阻止运行的问题。这种方法适用于那些希望简化管理员账户操作流程的用户,但需要注意可能带来的安全风险。通过创建并登录具有管理员权限的新账户,可以解决因系统安全设置导致的应用程序被阻止运行的问题。

mmoo_python的博客 1万+

Qt 中的 eventFilter 和 WinForms 中的 IMessageFilter

中的一个事件过滤器机制。通过为特定对象安装事件过滤器,可以拦截并处理该对象接收到的事件,包括鼠标事件、键盘事件、绘制事件等。需要根据具体的开发框架和需求选择合适的机制来处理事件或消息的拦截和处理。接口需要在应用程序的消息循环中注册,并实现其中的方法来处理特定类型的消息。是一种针对整个应用程序窗体消息的拦截机制,需要注册到消息循环中,并对特定类型的消息进行处理。方法,可以拦截和处理窗体接收到的消息,包括鼠标消息、键盘消息、窗体消息等。都可以实现事件或消息的拦截和处理,但在具体的实现和用法上存在差异。

qq_40098572的博客 304

基于STM32+4G模块设计的智能灌溉系统

当前智能灌溉系统分为三个部分:温湿度采集部分、灌溉系统部分、OneNet云平台。 灌溉系统部分增加刷卡功能,用户可以通过IC卡刷卡将金额刷到灌溉系统设备里,灌溉系统设备里会记录金额,并且在手机可视化页面上会显示当前的设备金额。 金额会随着时间进行递减,按分钟计费,如果计费到0,就无法启动灌溉,需要重新充值金额才能继续。

4512

WinForm中DefWndProc、WndProc与IMessageFilter的区别

Windows消息系统由3部分组成: 1.消息队列。Windows应用程序的消息是由Windows统一在一个消息队列中管理的。 2.消息循环。应用程序从Windows消息队列中获得自己的消息,并将其分配给窗口过程进行处理。 3.窗口过程。负责处理接收到的消息,每个窗口都有对应的窗口过程,负责截获消息并响应。WndProc是窗口过程函数,负责处理接收到的消息,在我们写代...

weixin_30952535的博客 169

VIIRS-NPP夜间灯光遥感数据下载和预处理

右侧搜索框搜索“按掩膜提取”,提取出夜光影像中国区域。将其转换为Albers积投影和重采样到400m。点击右上角Export,选择shp格式。最后点export导出就行。点击复制按钮,来到这个。,ctrl + v粘贴。将小于0.3的值置为0。下载好月合成产品后,

热爱分享,热爱记录 1万+

使用Python爬虫抓取政府网站政务信息:公告、通知的自动化抓取与分析

通过结合Requests、BeautifulSoup、Selenium等技术,你能够高效地抓取政府网站的数据,并通过MySQL存储与Pandas分析这些数据。通过自动化手段抓取这些信息,不仅可以提高数据收集的效率,还能够实时获取最新的政务动态,为政策研究、舆情分析等提供宝贵数据。我们将通过Python的Requests、BeautifulSoup、Selenium等工具,结合最新的技术实现一个完整的爬虫系统,帮助你轻松抓取并分析政务信息。通过爬虫,我们可以自动化地从指定网站上抓取公告、新闻、通知等信息。

2201_76125261的博客 1907

用ImessageFilter接口实现截获键盘消息

imessagefilter 接口 imessagefilter 接口允许应用程序在消息被调度到控件或窗体之前捕获它。 可以将实现 imessagefilter 接口的类添加到应用程序的消息泵中,以在消息被调度到控件或窗体之前将 它筛选出来或执行其他操作。若要将消息筛选器添加到应用程序的消息泵中,请使用 application 类中的 addmessagefilter 方法。

u011877729的专栏 720

【软件系统架构】系列六: SysML(系统建模语言)

SysML(系统建模语言)是OMG组织基于UML扩展的专用建模语言,用于支持复杂系统全生命周期建模。它包含9类标准图,核心建模元素包括块(Block)、端口接口、需求和约束等。与UML相比,SysML更适用于软硬件结合的复杂系统建模。作为MBSE的核心工具,SysML通过结构图、行为图、需求图和参数图实现系统设计、需求追踪和性能验证。虽然面临学习门槛高、工具成本高等挑战,但随着AI融合和国产化替代趋势,SysML在航空航天、汽车电子等领域的应用日益广泛。SysML v2将简化语法并提升互操作性,推动系统工程

moton2017的博客 2385

Winform中在Form上截取消息的两种方法

Winform中在Form上截取消息的两种方法 比较常用的是重载Form的DefWndProc方法,例如截取鼠标按下的消息:protected override void DefWndProc(ref Message m)        ...{            if ( m.Msg ==  0x0201 )            ...{                MessageB

BraveHeart专栏 1140

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

C# Winform中在Form上截取消息的两种方法

Winform中在Form上截取消息的两种方法

415

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

【转】Winform中在Form上截取消息的两种方法

原文见:Winform中在Form上截取消息的两种方法 比较常用的是重载Form的DefWndProc方法,例如截取鼠标按下的消息:protected override void DefWndProc(ref Message m)        {            if ( m.Msg ==  0x0201 )            {                MessageB

kolacowboy的程序生活 500

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

[转]Winform中在Form上截取消息的两种方法

比较常用的是重载Form的DefWndProc方法,例如截取鼠标按下的消息:protected override void DefWndProc(ref Message m){            if ( m.Msg == 0x0201 )            {                MessageBox.Show(m.Msg.ToString());

freeliver54的专栏 496

C# 鼠标和键盘事件截取

方法一:使用钩子首先在api声明的类里声明委托public delegate int procEntry(int nCode, int wParam, IntPtr lParam);截取鼠标消息关键代码:private IntPtr hand; public Form1() { InitializeComponent(); }

DruidElder的博客 1148
上一篇: 几种常见的软件命名规则
下一篇: ENUM WindowsMessages ID
dadahacker
博客等级 码龄20年 78粉丝 120原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值