[英]How to get access to main dialog's element in MFC? Element was created in visual editor VS 2012
I have created in VS 2012, in a visual resource editor, few components on the main form of the application (one of them is CStatic text). 我在VS 2012中的可视资源编辑器中创建了应用程序主窗体上的几个组件(其中一个是CStatic文本)。
I want now to access it, so I have wrote somewhere in my MainFrm.cpp (the code executes after clicking one of the buttons, so after everything was constructed): 我现在想访问它,所以我已经在MainFrm.cpp中写了一些地方(代码在单击按钮之一后执行,因此在构建所有东西之后):
CStatic * temp = (CStatic *) GetDlgItem(IDC_OPERATION_INFO);
temp->SetWindowText(text);
And while executing second line of the code, I get error: 在执行第二行代码时,出现错误:
Debug Assertion Failed!
Program: C:\Windows\system32\mfc110ud.dll
File: f:\\dd\vctools\vc7libs\ship\atlmfc\src\mfc\winocc.cpp
Line: 245
What I'm doing wrong? 我做错了什么?
The CStatic was created via visual editor, not in the code. CStatic是通过可视编辑器创建的,而不是通过代码创建的。 Ofc I see it on the application. Ofc我在应用程序上看到它。
The static control is probably on a CDialog or CFormView derived class, not CMainFrame. 静态控件可能在CDialog或CFormView派生类上,而不在CMainFrame上。 GetDlgItem only works for controls that are a child of the calling class. GetDlgItem仅适用于作为调用类的子级的控件。
A better way to access the control is to right click on it in the visual editor and select 'Add Variable'. 访问控件的更好方法是在可视编辑器中右键单击它,然后选择“添加变量”。 It will let you add a CStatic variable (like m_opinfo) to the correct parent class. 它将使您可以将CStatic变量(如m_opinfo)添加到正确的父类。 Then that class can call m_opinfo.SetWindowText(text). 然后,该类可以调用m_opinfo.SetWindowText(text)。
You should also note that GetDlgItem can be unsafe to use since it returns a temporary pointer. 您还应该注意,GetDlgItem可能会不安全使用,因为它会返回一个临时指针。 The pointer is only valid for the scope of the code (method) that is executing. 该指针仅对正在执行的代码(方法)的范围有效。 You should follow ScottMcP suggestion. 您应该遵循ScottMcP的建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.