如何在 WinAPI 中本机将图像添加到按钮C++(没有 MFC)

How to natively add an image to a button in C++ WinAPI (without MFC)?

本文关键字:C++ 按钮 没有 MFC 添加 图像 WinAPI 本机      更新时间:2023-10-16

好的,我想将图像与文本一起添加到按钮中,而无需在我的 RC 文件中制作按钮。这甚至可能吗,或者我是否需要使用 RC 文件来使按钮能够在其中放置图像?我的图像在"resource.h"中#define d,图像在"resources.rc"中声明。"main.cpp"和"resources.rc"都包含"resource.h"标头。我真的不想使用资源制作按钮,但如果它是制作带有图像文本的按钮的唯一方法,然后我会这样做。我需要知道的只是如何将图像放入 WinAPI 中的按钮中。

更新:

    将清单文件
  1. 添加到应用程序,清单文件应命名为YourApp.exe.manifest

  2. 将其添加到您的清单文件中(有关清单文件的更多信息,请单击此处 http://msdn.microsoft.com/en-us/library/bb773175%28VS.85%29.aspx):

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
    <assemblyIdentity
        version="1.0.0.0"
        processorArchitecture="*"
        name="CompanyName.ProductName.YourApplication"
        type="win32"
    />
    <description>Your application description here.</description>
    <dependency>
        <dependentAssembly>
            <assemblyIdentity
                type="win32"
                name="Microsoft.Windows.Common-Controls"
                version="6.0.0.0"
                processorArchitecture="*"
                publicKeyToken="6595b64144ccf1df"
                language="*"
            />
        </dependentAssembly>
    </dependency>
    </assembly>
    
  3. 将应用程序与ComCtl32.lib链接

  4. 将清单添加到应用程序资源文件CREATEPROCESS_MANIFEST_RESOURCE_ID RT_MANIFEST "YourApp.exe.manifest"

  5. 在WinMain开始时呼叫InitCommonControls()

结束更新

  1. 按钮创建的示例代码(图像+文本),由于加载位图而容易出现内存泄漏:

    HWND hwnd_button = CreateWindowEx(
            0,
            "BUTTON", //ascii
            "Button text",
            WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
            10, 
            145,
            50,
            50,
            hwnd_parent,
            NULL,
            //GetModuleHandle(NULL)
            (HINSTANCE)GetWindowLong(hwnd_parent, GWL_HINSTANCE),
            NULL);
    SendMessage((HWND) m_hWndButton,
            (UINT) BM_SETIMAGE,
            (WPARAM) IMAGE_BITMAP,
            (LPARAM) LoadBitmap(hInstance, MAKEINTRESOURCE(IDB_BITMAP1)));