Home > Net >  How to link an icon to a Rust Windows application
How to link an icon to a Rust Windows application

Time:01-08

In a Rust desktop application, some version of the window struct is always used, e.g., WNDCLASSW. When WNDCLASSW is defined, a class icon may be added through the struct member hIcon. The code excerpt below demonstrates how to include the icon stored in the file Icon.ico.

...
        let hicon: HICON = LoadImageW(
            0 as HINSTANCE, 
            wide_null("Icon.ico").as_ptr(), 
            IMAGE_ICON, 0, 0, LR_LOADFROMFILE
        ) as HICON;

        let hinstance = GetModuleHandleW(null_mut());

        let mut wc: WNDCLASSW = std::mem::zeroed();
        wc.lpfnWndProc = Some(window_proc);
        wc. hInstance = hinstance;
        wc.hIcon = hicon;
        wc.lpszClassName = name.as_ptr();
...

The icon file is loaded during the program execution and must be stored in the same folder as the exe file. If the icon file is missing, LoadImageW() returns a NULL handle. Setting hIcon to NULL is valid and causes the use of a standard system icon.

While this approach produces the required icon, the icon file is loaded during execution and must be delivered along with the exe file. This isn't an acceptable solution; the icon should be linked to the exe file and delivered within it.

How do I link an icon to a Rust Windows application and use it there?

I am aware of Screenshot with no embedded resource

The final step is to actually run embed-resource and have the icon linked into the executable image. A Screenshot with embedded resource


Note: The solution above uses the windows crate, which is designed for convenience and better safety. If you are using the winapi or windows-sys crate the core principles are still the same. The code in main.rs would have to be adjusted, though.

CodePudding user response:

This text complements Answer 1 by IInspectable, adding information for the users of winapi.

Create the resource file <name>.rc and build.rs as described in Answer 1, and place these files along with the icon file <name>.ico in the project root directory. Add the build dependency to embed-resource in Cargo.toml. The application built with these changes will embed the icon from the icon file.

To change the class icon that is shown in the taskbar, set the hIcon member in WNDCLASSW as follows:

hIcon = LoadImageW( 
    GetModuleHandleW(0 as LPCWSTR), // hInst; the .exe file
    MAKEINTRESOURCEW( 1 ),          // name; use the resource number in the .rc file
    IMAGE_ICON,                     // type
    0,                              // cx
    0,                              // cy
    0                               // fuLoad
    ) as HICON;
  • Related