VC创建一个透明窗口,并处理鼠标事件。
时间: 2023-08-29 17:04:42 浏览: 60
可以按照以下步骤创建一个透明窗口并处理鼠标事件:
1. 创建一个MFC项目,并在资源编辑器中添加一个对话框。
2. 在对话框类的头文件中添加以下代码:
```c++
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnPaint();
DECLARE_MESSAGE_MAP()
CBrush m_brush;
```
3. 在对话框类的源文件中添加以下代码:
```c++
BEGIN_MESSAGE_MAP(CMyDlg, CDialogEx)
ON_WM_LBUTTONDOWN()
ON_WM_ERASEBKGND()
ON_WM_PAINT()
END_MESSAGE_MAP()
void CMyDlg::OnLButtonDown(UINT nFlags, CPoint point)
{
CString str;
str.Format(_T("鼠标左键点击位置:(%d,%d)"), point.x, point.y);
AfxMessageBox(str);
}
BOOL CMyDlg::OnEraseBkgnd(CDC* pDC)
{
// 创建透明画刷
if (m_brush.m_hObject == NULL)
{
m_brush.CreateStockObject(NULL_BRUSH);
}
// 设置透明背景
pDC->FillRect(&m_rectClient, &m_brush);
return TRUE;
}
void CMyDlg::OnPaint()
{
CPaintDC dc(this); // device context for painting
// 创建透明画刷
if (m_brush.m_hObject == NULL)
{
m_brush.CreateStockObject(NULL_BRUSH);
}
// 绘制透明背景
dc.FillRect(&m_rectClient, &m_brush);
}
```
4. 在OnInitDialog()函数中添加以下代码:
```c++
// 设置对话框透明
SetWindowLong(m_hWnd, GWL_EXSTYLE, GetWindowLong(m_hWnd, GWL_EXSTYLE) | WS_EX_LAYERED);
SetLayeredWindowAttributes(RGB(255, 255, 255), 0, LWA_COLORKEY);
// 获取对话框客户区大小
GetClientRect(&m_rectClient);
// 设置对话框大小
SetWindowPos(NULL, 0, 0, m_rectClient.Width(), m_rectClient.Height(), SWP_NOMOVE | SWP_NOZORDER);
// 注册窗口类
WNDCLASS wndClass;
wndClass.style = CS_HREDRAW | CS_VREDRAW;
wndClass.lpfnWndProc = AfxWndProc;
wndClass.cbClsExtra = 0;
wndClass.cbWndExtra = 0;
wndClass.hInstance = AfxGetInstanceHandle();
wndClass.hIcon = NULL;
wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndClass.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
wndClass.lpszMenuName = NULL;
wndClass.lpszClassName = _T("MyTransparentWindow");
AfxRegisterClass(&wndClass);
// 创建窗口
CreateEx(WS_EX_LAYERED | WS_EX_TOOLWINDOW | WS_EX_TOPMOST, _T("MyTransparentWindow"), _T("MyTransparentWindow"), WS_POPUP, 0, 0, m_rectClient.Width(), m_rectClient.Height(), NULL, NULL, NULL);
// 设置窗口透明
SetLayeredWindowAttributes(RGB(255, 255, 255), 0, LWA_COLORKEY);
// 显示窗口
ShowWindow(SW_SHOW);
```
5. 编译并运行程序,即可看到一个透明窗口。当鼠标左键点击窗口时,会弹出一个消息框显示点击位置的坐标。