WinUI3:What is the right way to create and initialize UIElement Programatically with C++/Winrt

Harshithraj1871 1,516 Reputation points
2022-10-27T08:09:20.13+00:00

Hi,

I'm trying to bring up the WinUI3 window programmatically with c++/winrt. To bring up the first window, I created a Window variable and activated it, Like this

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

Window SampleWindow;  
SampleWindow.Activate();  

By this, I was able to bring up a window, my concern here is, is this the correct way to initialize a window and activate it[Programatically]? I could not find any official documentation for Initializing UIElement programmatically with C++. So is this the right way to do it?

Universal Windows Platform (UWP)
Windows App SDK
Windows App SDK
A set of Microsoft open-source libraries, frameworks, components, and tools to be used in apps to access Windows platform functionality on many versions of Windows. Previously known as Project Reunion.
737 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,584 questions
0 comments No comments
{count} votes

Accepted answer
  1. Junjie Zhu - MSFT 16,146 Reputation points Microsoft Vendor
    2022-10-28T03:21:15.767+00:00

    Hello @Harshithraj1871
    Welcome to Microsoft Q&A!

    Your code is ok.

    You can refer to the example of Window Class, and the startup method of MainWindow.

    winrt::Microsoft::UI::Xaml::Window window{ nullptr };  
      
    void App::OnLaunched(LaunchActivatedEventArgs const&)  
    {  
        window = make<MainWindow>();  
        window.Activate();  
    }  
    

    Thank you.
    Junjie


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful