将事件处理程序添加到C ++中的按钮 [英] Add event handler to button in c++

查看:83
本文介绍了将事件处理程序添加到C ++中的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在c ++中创建了一个按钮,如下所示:

I created a button in c++ as follows:

HWND btn = CreateWindow(
    "BUTTON",
    "OK",
    WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
    10,
    10,
    100, 
    100,
    hWnd, 
    NULL, 
    (HINSTANCE)GetWindowLong(hWnd, GWL_HINSTANCE),
    NULL);

该按钮显示在主窗口(hWnd)中,但我不知道如何或在何处为其提供事件处理程序.有什么帮助吗?

The button is displayed in the main window (hWnd) but I don't know how or where to give it an event handler. Any help please?

推荐答案

有三种方法可以检测到被单击的按钮.

There are three ways to detect the button being clicked.

  1. 首选方法是添加 WM_COMMAND 处理程序到按钮的父窗口的窗口过程.单击该按钮时,它会发送 BN_CLICKED 通知其父窗口.这在MSDN文档中针对按钮进行了描述:

  1. The preferred approach is to add a WM_COMMAND handler to the window procedure of the button's parent window. When the button is clicked, it sends a BN_CLICKED notification to its parent window. This is described in the MSDN documentation for buttons:

处理来自按钮的消息

来自按钮的通知消息

如果要将按钮添加到您不拥有的父窗口中,则可以使用

If you are adding the button to a parent window that you do not own, you can subclass the parent window using SetWindowsLongPtr(GWL_WNDPROC) or SetWindowSubClass(), and then you can handle messages that are sent to it, such as BN_CLICKED. This only works if the subclassing code runs in the same thread that owns the parent window.

或者,您可以将按钮本身子类化,而改为处理键盘和鼠标消息.

Alternatively, you can subclass the button itself and handle keyboard and mouse messages instead.

另一个选项是使用 SetWinEventHook() 要求接收 EVENT_OBJECT_INVOKED 事件.在事件回调过程中,提供的hwnd ID idChild 参数将标识正在调用的控件,例如单击的按钮.

Another option is to set an event hook using SetWinEventHook() asking to receive EVENT_OBJECT_INVOKED events. In the event callback procedure, the provided hwnd, ID, and idChild parameters will identify the control that is being invoked, such as a clicked button.

这篇关于将事件处理程序添加到C ++中的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆