gpt4 book ai didi

c++ - 应该如何从回调函数更新/返回值?

转载 作者:行者123 更新时间:2023-11-30 17:42:26 25 4
gpt4 key购买 nike

我已通过以下方式注册回调:SetWindowLongW(hWindow, GWL_WNDPROC, (LONG)WindowCallback);

我在那里收到消息没有问题。我在回调内部有 if() 样式代码,如下所示:

if (MSG == 1)
{

*boolptr = true;
...
} else if(MSG == 2) {
if (*boolptr == true)
return;

// do stuff
}

变量的定义如下(全局,在#includes右侧..)

volatile bool         boolVar = false;
volatile bool* volatile boolptr = &boolVar;

如果我在 main() 中等待 *boolptr 为 TRUE ,一切都很好,但如果我在应该更改的同一个回调中等待它,则它不起作用。显然我不理解这里的一些概念,所以我请求帮助或解释为什么它不起作用。

值为 2 的 MSG 总是先到达,然后经过一些处理后值为 1 的 MSG 到达。一段时间后,同样的事情发生,但我不想做相同的处理并浪费 CPU 周期,因此我需要知道 MSG 是否[1] 正在跟踪它并返回。希望你能理解我。

谢谢!

最佳答案

你的描述遗漏了很多细节,但我想我明白你想要什么。CreateWindow() API 函数的最后一个参数可用于将指向回调的指针传递给某个外部变量:

// MAKE SURE this variable stays in scope throughout the lifetime of your window !
// Make it global or static
bool myVar;

// let's create an overlapped window of some class with size 400 x 300
HWND hWnd = CreateWindow("My class name", "My Title",
WS_VISIBLE | WS_BORDER| WS_OVERLAPPED | WS_CAPTION |
WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,
0,0, 400, 300, NULL, NULL, GetModuleHandle(NULL), &myVar);

然后在回调中,您可以在 WM_CREATE 消息中访问它:

// ... start of your callback

// get a pointer to your variable here and use it in all messages
// *except* WM_CREATE that sets it during window instance creation
bool *pMyVar = (bool *)GetWindowLongPtr(hWnd, GWLP_USERDATA);

switch(uMsg)
{
case WM_CREATE:
{
// get your pointer from the CREATESTRUCT passed in
// and store it in the user data area of your window class
// note: your WNDCLASS should have its cbWndExtra = sizeof(void *);
CREATESTRUCT *pC = (CREATESTRUCT *)lParam;
SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG)pC->lpCreateParams);
// ....
}
break;

case 1 : // VERY bad choice for a message, use WM_USER+1 instead
*pMyVar = true;
break;
// ... rest of your callback

这就是你想要的吗?

编辑:好的,这是您想看的类(class):

class MyClass
{
public:
MyClass() : _hasRun(false) { }

void DoStuff(HWND hW, UINT uMsg)
{
if (!_hasRun)
{
_hasRun = true;
// ... do your work here, you have the window handle and the message
}
}

private:
bool _hasRun;
};

现在,在您的 main 中创建此类的实例并将其保存在静态或全局变量中:

MyClass *pC = new MyClass;

然后,将其传递给回调,如我在开头所示,然后始终调用它。 DoStuff 成员函数将检查消息并根据消息的内容执行一次您想要的操作。即使您将其保留在全局中并始终从回调中调用此全局,功能也将是相同的。

// ... callback code before you handle any message
pC->DoStuff(hWnd, uMsg);
// ... rest of callback code

关于c++ - 应该如何从回调函数更新/返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20577066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com