孙鑫VC++深入详解:Lesson8 Part3---如何让对话框捕获WM_KEYDOWN消息?

在MFC的对话框程序中,由于Windows内部处理,通常无法直接捕获按键消息。为了解决这个问题,可以子类化对话框,并覆盖基类的`ProcessMessageFilter()`虚函数,从而接管特定的Windows消息响应,实现按键消息的捕获。通过在自定义的CWinSunApp类中增加`ProcessMessageFilter`方法,可以成功捕获并处理键盘输入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


因为对话框程序中,某些特点的消息,如按键消息被Windows内部的对话框过程处理了,即基类完成了或者被发送给子控件处理,所以在对话框类中就不能捕获到按键消息


解决办法:在子类中覆盖基类的特定消息过滤响应函数.

在MFC中,用虚函数ProcessMessageFilter()来过滤或者响应菜单和对话框的特定Windows消息.

在子类中覆盖它,接管消息响应.

本例中,在CWinSunApp类中增加虚函数 ProcessMessageFilter

//覆盖基类的虚函数,接管消息
BOOL CWinSunApp::ProcessMessageFilter(int code, LPMSG lpMsg) 
{
	// TODO: Add your specialized code here and/or call the base class
    
	if(m_hwndDlg!=NULL)
	{
		if(lpMsg->message==WM_KEYDOWN)
			AfxMessageBox("捕获WM_KEYDOWN成功!");
	}
	
	return CWinApp::ProcessMessageFilter(code, lpMsg);
}

WinSunApp.h

// WinSun.h : main header file for the WINSUN application
//

#if !defined(AFX_WINSUN_H__025D80ED_531B_42C3_8C9F_1EB3093C7BC9__INCLUDED_)
#define AFX_WINSUN_H__025D80ED_531B_42C3_8C9F_1EB3093C7BC9__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#ifndef __AFXWIN_H__
	#error include 'stdafx.h' before including this file for PCH
#endif

#include "resource.h"		// main symbols

/////////////////////////////////////////////////////////////////////////////
// CWinSunApp:
// See WinSun.cpp for the implementation of this class
//

class CWinSunApp : public CWinApp
{
public:
	HWND m_hwndDlg;
	CWinSunApp();

// Overrides
	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CWinSunApp)
	public:
	virtual BOOL InitInstance();
	virtual BOOL ProcessMessageFilter(int code, LPMSG lpMsg);
	//}}AFX_VIRTUAL

// Implementation

	//{{AFX_MSG(CWinSunApp)
		// NOTE - the ClassWizard will add and remove member functions here.
		//    DO NOT EDIT what you see in these blocks of generated code !
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};


/////////////////////////////////////////////////////////////////////////////

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_WINSUN_H__025D80ED_531B_42C3_8C9F_1EB3093C7BC9__INCLUDED_)

WinSunApp.cpp

// WinSun.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "WinSun.h"
#include "WinSunDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CWinSunApp

BEGIN_MESSAGE_MAP(CWinSunApp, CWinApp)
	//{{AFX_MSG_MAP(CWinSunApp)
		// NOTE - the ClassWizard will add and remove mapping macros here.
		//    DO NOT EDIT what you see in these blocks of generated code!
	//}}AFX_MSG
	ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CWinSunApp construction


CWinSunApp::CWinSunApp()
{
	// TODO: add construction code here,
	// Place all significant initialization in InitInstance
}

/////////////////////////////////////////////////////////////////////////////
// The one and only CWinSunApp object

CWinSunApp theApp;

/////////////////////////////////////////////////////////////////////////////
// CWinSunApp initialization

BOOL CWinSunApp::InitInstance()
{
	AfxEnableControlContainer();

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	//  of your final executable, you should remove from the following
	//  the specific initialization routines you do not need.

#ifdef _AFXDLL
	Enable3dControls();			// Call this when using MFC in a shared DLL
#else
	Enable3dControlsStatic();	// Call this when linking to MFC statically
#endif

	CWinSunDlg dlg;
	m_pMainWnd = &dlg;
	int nResponse = dlg.DoModal();
	if (nResponse == IDOK)
	{
		// TODO: Place code here to handle when the dialog is	
		//  dismissed with OK
	}
	else if (nResponse == IDCANCEL)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with Cancel
	}

	// Since the dialog has been closed, return FALSE so that we exit the
	//  application, rather than start the application's message pump.

	//将CWinSunApp类的成员变量设置为NULL
	m_hwndDlg =NULL;

	return FALSE;
}

//覆盖基类的虚函数,接管消息
BOOL CWinSunApp::ProcessMessageFilter(int code, LPMSG lpMsg) 
{
	// TODO: Add your specialized code here and/or call the base class
    
	if(m_hwndDlg!=NULL)
	{
		if(lpMsg->message==WM_KEYDOWN)
			AfxMessageBox("捕获WM_KEYDOWN成功!");
	}
	
	return CWinApp::ProcessMessageFilter(code, lpMsg);
}

WinSunDlg.h

// WinSunDlg.h : header file
//

#if !defined(AFX_WINSUNDLG_H__9DC85391_A9DD_4A1E_8380_6A32A3CF15EF__INCLUDED_)
#define AFX_WINSUNDLG_H__9DC85391_A9DD_4A1E_8380_6A32A3CF15EF__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

/////////////////////////////////////////////////////////////////////////////
// CWinSunDlg dialog

class CWinSunDlg : public CDialog
{
// Construction
public:
	CWinSunDlg(CWnd* pParent = NULL);	// standard constructor

// Dialog Data
	//{{AFX_DATA(CWinSunDlg)
	enum { IDD = IDD_WINSUN_DIALOG };
		// NOTE: the ClassWizard will add data members here
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CWinSunDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);	// DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	HICON m_hIcon;

	// Generated message map functions
	//{{AFX_MSG(CWinSunDlg)
	virtual BOOL OnInitDialog();
	afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
	afx_msg void OnPaint();
	afx_msg HCURSOR OnQueryDragIcon();
	afx_msg void OnDestroy();
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_WINSUNDLG_H__9DC85391_A9DD_4A1E_8380_6A32A3CF15EF__INCLUDED_)

WinSunDlg.cpp

// WinSunDlg.cpp : implementation file
//

#include "stdafx.h"
#include "WinSun.h"
#include "WinSunDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CWinSunDlg dialog

CWinSunDlg::CWinSunDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CWinSunDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CWinSunDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CWinSunDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CWinSunDlg)
		// NOTE: the ClassWizard will add DDX and DDV calls here
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CWinSunDlg, CDialog)
	//{{AFX_MSG_MAP(CWinSunDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_DESTROY()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CWinSunDlg message handlers

BOOL CWinSunDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here

	//将对话框的句柄传递到CWinSunApp类中
	((CWinSunApp*)AfxGetApp())->m_hwndDlg =this->m_hWnd;
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CWinSunDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CWinSunDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CWinSunDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CWinSunDlg::OnDestroy() 
{
	CDialog::OnDestroy();
	
	// TODO: Add your message handler code here
      //对话框窗口销毁后,将CWinSumApp类中的变量m_hwndDlg置为NULL
		((CWinSunApp*)AfxGetApp())->m_hwndDlg =NULL;
}

//---

//---


//---编译运行,试着按下键盘任意一个键:

//---

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值