所以,我在任何地方都找不到这个问题的答案。假设,为了我的理智,我想在单独的文件中处理与使用 Win32 API 创建的按钮交互的代码。
目前我的 WinMain 文件中有以下内容:
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
/*
Added
*/
//creating a windows in order to display a button
case WM_CREATE:
{
button = CreateWindowA("button", "Identify Devices on Current Network",
WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
10, 10, 300, 25,
hWnd, (HMENU) ID_BTNIDCN, GetModuleHandle(NULL), NULL);
}
break;
/*
Added
*/
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
/*
Added
*/
case ID_BTNIDCN:
{
queryDevices(hWnd); //this is in another file
//Any action to take when button is presed
//In this case, creating a message box to display testing, with title test.
//MessageBoxA(hWnd, "Test", "Testing", MB_OK);
}
break;
我的查询设备文件中有这个:
#include "stdafx.h"
#include "commonheader.h"
#include "targetver.h"
#include "resource.h"
using namespace std;
//Handing the Button Press
void queryDevices(HWND hWnd)
{
MessageBoxA(hWnd, "Test", "Testing", MB_OK);
};
我还有一个包含相关代码的通用 .h 文件:
#pragma once
#include "resource.h"
//Custom Files to be included
#include "customfile.cpp"
//Custom Functions
//IdentifyDevicesonCurrentNetwork.cpp
void queryDevices(HWND hWnd);
这里的想法是让您按下按钮时执行的代码包含在另一个文件中,这样编辑和修改就相对容易,而不会以某种方式搞砸 WinMain 文件。
有什么建议吗? Visual Stupid 提示我的函数已经有一个主体。
最佳答案
当您的编译器翻译您的源文件 (.cpp
) 时,它会为您的函数体生成代码。如果您现在再次将此文件包含在头文件中,则在转换头文件时会再次生成函数体的相同代码。
这本质上导致具有两个相同的功能,并且链接器不知道如何处理它们。
要解决此问题,只需从头文件中删除 #include "customfile.cpp"
。通常,切勿在任何头文件中包含任何源文件 (.cpp
)。
关于c++ - 如何使用存在于另一个文件中的 WndProc 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46278475/