首页 > c++ > 如何将数据类型传递给Win32 C ++中的资源(.rc)文件?

如何将数据类型传递给Win32 C ++中的资源(.rc)文件? (How do I pass a data type to a resource (.rc) file in Win32 C++?)

问题

我想在Win32应用程序中居中一个对话框,但是在将常量传递给我的resource.rc文件时遇到了麻烦。我在resource.h中做了以下声明:

const int SCREENX = GetSystemMetrics(SM_CXSCREEN);

但是,当我在我的.rc文件(下面)和构建中用SCREENX替换100时,我得到:错误RC2108:预期的数值对话框常量

#include <windows.h>
#include "resource.h"
#include "afxres.h"

// I'd like to replace "100" with "GetSystemMetrics(SM_CXSCREEN)"
ID_ABOUT DIALOG DISCARDABLE  100, 0, 237, 87
STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "About"
FONT 10, "MS Sans Serif"

BEGIN
    GROUPBOX "Contact", IDC_CONTACT, 7, 43, 98, 39, WS_CHILD | WS_VISIBLE
    LTEXT    "My info", IDC_CONTACT, 16, 53, 85, 25, WS_CHILD | WS_VISIBLE
END

我也不能直接在所需位置使用GetSystemMetrics(SM_CXSCREEN)(相同的错误)。

我认为将数据类型传递给.rc是常规的,所以我必须在这里遗漏一些基本的东西。(资源文件让我头疼不已。)谢谢!

解决方法

资源文件被编译为一堆存储在可执行文件中的静态数据。例如,可以将对话框资源编译为DLGTEMPLATE结构。

换句话说,编译资源中的所有内容都是常量。

GetSystemMetrics(SM_CXSCREEN)不是一个常数。它在运行时评估当前屏幕宽度(以像素为单位)。

正如另一个答案所说,要使对话框居中,请使用DS_CENTER样式或句柄WM_INITDIALOG

问题

I'd like to center a dialog box in my Win32 application, but am having trouble passing constants to my resource.rc file. I make the following declaration in resource.h:

const int SCREENX = GetSystemMetrics(SM_CXSCREEN);

However, when I replace 100 with SCREENX in my .rc file (below) and build, I get: error RC2108: expected numerical dialog constant.

#include <windows.h>
#include "resource.h"
#include "afxres.h"

// I'd like to replace "100" with "GetSystemMetrics(SM_CXSCREEN)"
ID_ABOUT DIALOG DISCARDABLE  100, 0, 237, 87
STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "About"
FONT 10, "MS Sans Serif"

BEGIN
    GROUPBOX "Contact", IDC_CONTACT, 7, 43, 98, 39, WS_CHILD | WS_VISIBLE
    LTEXT    "My info", IDC_CONTACT, 16, 53, 85, 25, WS_CHILD | WS_VISIBLE
END

Neither can I use GetSystemMetrics(SM_CXSCREEN) directly in the desired location (same error).

I'd think it would be routine to pass data types to .rc, so I must be missing something basic here. (Resource files are giving me no end of headaches.) Thank you!

解决方法

A resource file is compiled into a bunch of static data that is stored in your executable. For example, a dialog resource might be compiled into a DLGTEMPLATE structure.

In other words, everything in a compiled resource is a constant.

GetSystemMetrics(SM_CXSCREEN) is not a constant. It evaluates to the current screen width in pixels at run-time.

As the other answer says, to center your dialog use the DS_CENTER style or handle WM_INITDIALOG.

相似信息