(Winapi C++) 如何在没有全局变量的情况下将数据从一个窗口传递到另一个窗口? [英] (Winapi C++) How to pass data from window to window without globals?

查看:29
本文介绍了(Winapi C++) 如何在没有全局变量的情况下将数据从一个窗口传递到另一个窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试对此进行研究,但我仍然很困惑.我真的不想使用全局变量,但即使在 msdn 站点上,他们也说将其设置为全局以从对话框回调中访问它".有什么办法可以在堆上创建内存并将指针传递给新创建的对话框吗?我希望对话框能够更改通过指针访问的数据.

I've tried to do research on this and I'm still very confused. I really don't want to use globals, but even on the msdn site they say "set this to global to access it from the dialog box callback". Is there someway I can create memory on the heap and pass a pointer to a newly created dialog box? I want the dialog box to be able to change the data that is accessed through the pointer.

推荐答案

如果您使用 DialogBoxParam,您可以在 dwInitParam 中传递指针:

If you're using the DialogBoxParam you could pass the pointer in the dwInitParam:

DialogBoxParam(hInstance, 
               MAKEINTRESOURCE(IDD_DIALOG), 
               hwndParent, 
               YourDialogFunc, 
               dwInitParam);

然后您将从对话框回调中访问数据:

Then you would access the data from your dialog callback:

INT_PTR CALLBACK YourDialogProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  switch(uMsg) [
    case WM_INITDIALOG:
      // the lParam parameter will contain the data sent through the dwInitParam
      return 1;
    break;
  }
  return 0;
}

如果您使用CreateWindowEx,您将通过CREATESTRUCT 中的lpCreateParams 发送数据,该lpParam代码>参数.

If you use the CreateWindowEx you would sent you data through the lpCreateParamsin the CREATESTRUCT being sent through the lpParam parameter.

 LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    switch(uMsg) [
      case WM_CREATE:
      {
        CREATESTRUCT *pCreate = reinterpret_cast<CREATESTRUCT*>(lParam);
        int* userdata = reinterpret_cast<int*>(pCreate->lpCreateParams);
        // store the pointer in the instance data of the window
        // so it could always be retrieved by using GetWindowLongPtr(hwnd, GWLP_USERDATA) 
        SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)userdata);
      }
      break;
    }
    return DefWindowProc(hwnd, uMsg, wParam, lParam);
 }

这篇关于(Winapi C++) 如何在没有全局变量的情况下将数据从一个窗口传递到另一个窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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