Skip to content
The Chat Archive
o1-preview-2024-09-12· OpenAI WildChat-4.8M (AI2)

Tenho seguinte código winui c++ xaml <?xml version="1.0" encoding="utf-8"?> <Window…

  1. User

    Tenho seguinte código winui c++

    xaml

    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
        <Button x:Name="myButton" Click="myButton_Click">Click Me</Button>
    </StackPanel>
    

    mainWindow.xaml.cpp

    #include "pch.h" #include "MainWindow.xaml.h" #if __has_include("MainWindow.g.cpp") #include "MainWindow.g.cpp" #endif

    using namespace winrt; using namespace Microsoft::UI::Xaml;

    // To learn more about WinUI, the WinUI project structure, // and more about our project templates, see: http://aka.ms/winui-project-info.

    namespace winrt::DataIntegrityTools::implementation { int32_t MainWindow::MyProperty() { throw hresult_not_implemented(); }

    void MainWindow::MyProperty(int32_t)
    {
        throw hresult_not_implemented();
    }
    
    void MainWindow::myButton_Click(IInspectable const&, RoutedEventArgs const&)
    {
        myButton().Content(box_value(L"Clicked"));
    }
    

    }

    mainwindow.xaml.h

    #pragma once

    #include "MainWindow.g.h"

    namespace winrt::DataIntegrityTools::implementation { struct MainWindow : MainWindowT { MainWindow() { // Xaml objects should not call InitializeComponent during construction. // See https://github.com/microsoft/cppwinrt/tree/master/nuget#initializecomponent }

        int32_t MyProperty();
        void MyProperty(int32_t value);
    
        void myButton_Click(IInspectable const& sender, Microsoft::UI::Xaml::RoutedEventArgs const& args);
    };
    

    }

    namespace winrt::DataIntegrityTools::factory_implementation { struct MainWindow : MainWindowT<MainWindow, implementation::MainWindow> { }; }

    Como posso alterar o icone e titulo da barra de titulos do app ?

  2. Assistant

    Para alterar o ícone e o título da barra de títulos do seu aplicativo WinUI 3 em C++/WinRT, você precisa acessar o identificador da janela (HWND) e usar APIs da Win32 para definir o ícone, e usar o AppWindow para definir o título.

    Aqui está um passo a passo de como você pode fazer isso:

    1. Inclua os cabeçalhos necessários:

    No seu arquivo MainWindow.xaml.h, certifique-se de incluir os seguintes cabeçalhos:

    #include <winrt/Microsoft.UI.Xaml.h>
    #include <winrt/Microsoft.UI.Windowing.h>
    #include <winrt/Windows.Graphics.h>
    #include <winrt/Microsoft.UI.Win32Interop.h>
    #include <winrt/windows.ui.viewmanagement.h>
    #include <winrt/Windows.UI.ViewManagement.Core.h>
    #include <winrt/Windows.Foundation.h>
    #include <winrt/Windows.Foundation.Metadata.h>
    #include <windows.h>
    #include <winrt/base.h>
    

    2. Adicione uma função para obter o HWND da janela:

    Adicione uma função privada na sua classe MainWindow para obter o identificador da janela (HWND):

    private:
        HWND GetWindowHandle();
    

    Em seguida, implemente essa função no seu arquivo MainWindow.xaml.cpp:

    HWND MainWindow::GetWindowHandle()
    {
        HWND hwnd{ nullptr };
        auto windowNative{ this->try_as<::IWindowNative>() };
        winrt::check_bool(windowNative);
        windowNative->get_WindowHandle(&hwnd);
        return hwnd;
    }
    

    3. Defina o título e o ícone da janela:

    Adicione uma função para definir o título e o ícone da janela. Você pode chamar essa função no construtor da sua janela principal ou em um evento de inicialização.

    void MainWindow::SetWindowTitleAndIcon()
    {
        // Obtenha o HWND da janela
        HWND hwnd = GetWindowHandle();
    
        // Defina o título da janela usando AppWindow
        auto windowId = winrt::Microsoft::UI::Win32Interop::GetWindowIdFromWindow(hwnd);
        auto appWindow = winrt::Microsoft::UI::Windowing::AppWindow::GetFromWindowId(windowId);
        appWindow.Title(L"Meu Aplicativo");
    
        // Carregue o ícone (substitua "IDI_MYICON" pelo ID do seu recurso de ícone)
        HICON hIcon = LoadIconW(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_MYICON));
    
        // Verifique se o ícone foi carregado com sucesso
        if (hIcon)
        {
            // Defina o ícone da janela usando SendMessage
            SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
            SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
        }
    }
    

    4. Certifique-se de ter um recurso de ícone definido:

    No seu arquivo de recursos (.rc), defina o ícone com o ID IDI_MYICON. Por exemplo:

    #define IDI_MYICON 101
    IDI_MYICON ICON "path_to_your_icon.ico"
    

    5. Chame a função para definir o título e o ícone:

    No construtor da sua MainWindow, chame a função SetWindowTitleAndIcon();

    MainWindow::MainWindow()
    {
        InitializeComponent();
        SetWindowTitleAndIcon();
    }
    

    6. Verifique se o seu aplicativo inclui o arquivo de recursos:

    Certifique-se de que o seu projeto está compilando o arquivo de recursos (.rc) que contém o ícone. Isso pode ser feito adicionando o arquivo de recursos ao seu projeto no Visual Studio.

    Resumo:

    • Título da Janela: Use AppWindow.Title para definir o título da janela.
    • Ícone da Janela: Carregue o ícone usando LoadIconW e defina-o usando SendMessage com WM_SETICON.

    Exemplo completo:

    // MainWindow.xaml.h
    #pragma once
    
    #include "MainWindow.g.h"
    #include <winrt/Microsoft.UI.Xaml.h>
    #include <winrt/Microsoft.UI.Windowing.h>
    #include <winrt/Windows.Graphics.h>
    #include <winrt/Microsoft.UI.Win32Interop.h>
    #include <windows.h>
    
    namespace winrt::DataIntegrityTools::implementation
    {
        struct MainWindow : MainWindowT<MainWindow>
        {
            MainWindow();
    
            int32_t MyProperty();
            void MyProperty(int32_t value);
    
            void myButton_Click(IInspectable const& sender, Microsoft::UI::Xaml::RoutedEventArgs const& args);
    
        private:
            void SetWindowTitleAndIcon();
            HWND GetWindowHandle();
        };
    }
    
    // MainWindow.xaml.cpp
    #include "pch.h"
    #include "MainWindow.xaml.h"
    #include "Resource.h"
    
    using namespace winrt;
    using namespace Microsoft::UI::Xaml;
    
    namespace winrt::DataIntegrityTools::implementation
    {
        MainWindow::MainWindow()
        {
            InitializeComponent();
            SetWindowTitleAndIcon();
        }
    
        HWND MainWindow::GetWindowHandle()
        {
            HWND hwnd{ nullptr };
            auto windowNative{ this->try_as<::IWindowNative>() };
            winrt::check_bool(windowNative);
            windowNative->get_WindowHandle(&hwnd);
            return hwnd;
        }
    
        void MainWindow::SetWindowTitleAndIcon()
        {
            HWND hwnd = GetWindowHandle();
    
            // Defina o título da janela
            auto windowId = winrt::Microsoft::UI::Win32Interop::GetWindowIdFromWindow(hwnd);
            auto appWindow = winrt::Microsoft::UI::Windowing::AppWindow::GetFromWindowId(windowId);
            appWindow.Title(L"Meu Aplicativo");
    
            // Carregue e defina o ícone da janela
            HICON hIcon = LoadIconW(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_MYICON));
            if (hIcon)
            {
                SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
                SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
            }
        }
    
        // ... restante do código ...
    }
    

    Notas adicionais:

    • Recursos: Certifique-se de que o ícone está incluído nos recursos do aplicativo e que o ID do recurso corresponde ao usado no código (IDI_MYICON neste exemplo).
    • Tamanho do Ícone: Você pode precisar fornecer diferentes tamanhos de ícones para ICON_SMALL e ICON_BIG para melhor aparência em diferentes situações.
    • Exceções e Erros: Adicione verificações de erro adicionais conforme necessário para garantir a robustez do seu aplicativo.

    Seguindo esses passos, você conseguirá alterar o ícone e o título da barra de títulos do seu aplicativo WinUI 3 em C++/WinRT.