The first step during Windows app development is determining which Windows app development tools you will use. Let’s do a WinForms vs WPF vs UWP comparison and look at a better alternative from Embarcadero.
Microsoft currently provides three different frameworks and solutions for Windows development that we will cover in this article. The three solutions are WinForms, WPF, and UWP. There might be a misconception that UWP is a framework like WinForms and WPF but that is not the case. UWP is a much broader solution but has now been deprecated by Microsoft.
What is WinUI 3?
Microsoft WinUI 3 is the latest UI toolkit from Microsoft. It aims to provide an alternative to the MFC, WinForms, and WPF technologies. Written primarily in C++ WinUI 3 is aimed to be a performant library and toolkit which will enable developers using things like WinForms to migrate their apps to use this more recent offering. The WinUI 3 library ships with Microsoft’s Windows App SDK – which was previously called “Project Reunion”. Compared to UWP, for example, Win UI 3 decouples or removes the dependence on the operating system “including the core framework, composition, and input layers of the UX stack” [1].
At the time of writing there are two versions of WinUi available: WinUI 2 and WinUI3. The WinUI 2 version is tightly connected to the Windows 10 and later SDKs. Win UI 3 attempts to break away from that dependency.
What Is Windows Forms (WinForms)?
Windows Forms, also known as WinForms, is a solution with .NET Framework that allows developers to create forms and controls for Windows applications. The original .NET framework has been deprecated. This does not mean .Net (or Dot Net) is going away, there is currently a push to unify the .NET and .NET Core technologies into a new version, .NET 5. There are some significant differences between .NET5 and .NET5 though, for example WebForms (a web based version of WinForms) has been pushed aside in favor of Blazor which is a declarative framework for creating interactive web pages using the C# language.
WinForms provides a wide variety of controls, including buttons, text boxes, and labels. WinForms also supports data binding, which enables developers to bind controls to data sources such as databases and XML files. WinForms applications can be created in Visual Studio by using the WinForms Designer. WinForms applications can also be created in code by using the System.Windows.Forms namespace. WinForms is a tool for developing Windows applications.
Know the benefits when you install Visual Studio and how it can help you get on your way to application development.
What is Windows Presentation Foundation (WPF)?
Windows Presentation Foundation (WPF) is a Microsoft Windows application programming interface (API) that provides a managed-code framework for developing Windows applications. WPF, previously known as “Avalon”, was initially released as part of the deprecated .NET Framework 3.0 in 2006. WPF uses XAML, an XML-based language, to define and link various UI elements. WPF applications can be deployed as standalone desktop programs or hosted as an embedded object in a Windows Presentation Foundation browser application (XBAP). WPF aimed to unify a number of common user interface platform features, including 2D/3D graphics, rendering, animation, and stylistic effects into one integrated platform. It also aims to make it easier to create connected applications such as those that integrate with Windows Workflow Foundation and Windows Communication Foundation. Windows Presentation Foundation is included in the Windows SDK.
WinForms | WPF |
You can use the native Windows library to access common controls. | It uses DirectX with XAML support for programming. |
No need to use a markup language for app designing. Instead, use event-driven controls to create the app’s design. | You need to use a markup language for complex user interfaces. |
Programming can slower than WPF. | Supports apps with complex features |
It can only develop and design Windows applications. | You can develop and design both Windows apps and web-based applications. |
It comes with limited controls which are also hard to customize. | WPF offers UI customization and controls which allow you to write an app from scratch. |
Difficult to separate UI from back-end logic. | Possible to separate UI from back-end logic. |
It does not have the user interface visualization feature. | The user interface visualization feature allows you to manage large sets of data. |
You can write apps on a smaller memory footprint but they still usually require a .NET runtime. | Requires more memory than WinForms for app development. |
What is the Universal Windows Platform (UWP)?
Universal Windows Platform (UWP) is a Microsoft application development platform. It allowed developers to create applications that can run on any Windows 10 device, including PCs, tablets, phones, and others. UWP apps are built using Universal Windows Platform app development tools such as Visual Studio and Microsoft Expression Blend. Universal Windows Platform app development is also supported by a number of third-party toolsets. Universal Windows Platform apps can be distributed through the Microsoft Store, as well as other app stores and channels. Universal Windows Platform apps could be developed using a variety of programming languages and frameworks, including C++, C#, and Visual Basic.NET. The principles behind UWP seem to have been to have a user interface and experience which would work on a variety of Microsoft platforms, especially the Xbox and the much-loved but ultimately doomed Windows phone.
Despite the “universal” part of the name UWP apps could only run on devices running Windows 10 and Windows 11. They can’t run on earlier versions of Windows such as Windows 8. The release of UWP did attract some criticism [4] due to the intention that UWP apps would be available via the Windows Store which meant that some limits would need to be put in place on the app’s capabilities in order to be in compliance with the Windows Store’s restrictions. The objections were particularly vocal amongst the gaming community where their modus operandi was to push the limits of the computer’s hardware and operating system to the absolute limits which ran counter to more channeled, focused, curated approach of UWP and the Windows Store in general. This resistance seemed to have enough traction among developers that by June 2019 Microsoft announced that Win32 apps would also be able to appear in the Windows Store along with other lessening of the confinements [5].
WinForms Vs. WPF Vs. UWP – which one to use?
From our perspective the answer is none of them – well at least not directly. Choosing between WinForms, WPF, and basing something on UWP can all be very confusing. It doesn’t help that UWP has been deprecated by Microsoft [3] and there is some current state of flux between .NET 4, .NET Core, and .NET5. To be clear, these development choices are not bad, but why chase around a moving target or have to decide which Microsoft technology you adopt. It can be confusing, there is a process of rationalization by Microsoft to try and narrow down choices to be less confusing too, but why not choose an option that is designed to insulate you from needing to understand the available frameworks? Why not go for an option which embraces the best of the available UI, UX, APIs and SDKs and encapsulates them in a way which is both cohesive, comprehensive, and easy to understand?
Software development budgets are tight and dealing with unneeded technical debt can be time consuming. So what is the alternative?
What is the best alternative to WinForms Vs. WPF Vs. UWP?
The best alternative for Windows Forms, WPF, and UWP, in my opinion, is RAD Studio with Delphi. Delphi is an IDE for rapidly developing high-performance Windows and cross-platform applications. It offers a visual design tool and features that developers love, making it one of the most advanced IDEs on the market. Delphi makes it easy to create stunning applications with amazing performance. With its intuitive design tools, you can quickly develop beautiful user interfaces and rich functionality. Additionally, Delphi’s cross-platform capabilities allow you to deploy your applications to a wider audience. So whether you’re looking to develop Windows applications or cross-platform applications, Delphi is the IDE for you. We also have a whitepaper which shows the differences in productivity between Delphi, WPF, and Electron.
What are some of the powerful features of Delphi?
Single Code Base
Create apps for all major platforms with less coding effort. Write once, compile everywhere.
Windows 11
Modernize VCL apps for Windows 11 with up-to-date user interface controls, WinRT APIs, and HighDPI-related features
Remote Desktop
Collaborate more effectively with remote teams using improved remote desktop support for VCL and IDE
High DPI & 4K
High-DPI support in the IDE, with full support for the latest 4k+ monitors, and cleaner and sharper fonts and icons throughout. Improved FMX High-DPI support for Windows and Desktop with a visibly superior desktop UI
iOS and macOS
macOS 64bit ARM compiler and toolchain that can build universal binaries including Intel/ARM versions for AppStore submissions
Android
Support for the latest Android 30 API and latest Billing APIs, and migration to use the AndroidX libraries. Android support for multiple classes.dex files, simplifying integration of external Android dependencies
Accessible Data
Connect to over 20 databases natively with FireDAC’s high speed direct access, including InterBase, SQLite, MySQL, SQL Server, Oracle, PostgreSQL, DB2, SQL Anywhere, Advantage DB, Firebird, Access, Informix, MongoDB and more
Faster Coding
Smarter code navigation when refactoring. Auto code completion with Tab key. LSP awareness of Include files. Auto restart of LSP server. Class helper support. Array suggestions when assigning arrays
Productivity
VCL Styles with design-time support: Prototype stylish UIs even faster by seeing immediately at design-time how your styled forms and controls will look when running.
Linux
Develop both server and FireMonkey GUI applications for Linux
User Experience
Completely rebuilt Welcome Page with a native look and feel, and a UI that fits the IDE, and customizable layout and content
Cloud Aware
Use the HTTP and REST client libraries, available on all platforms, to invoke REST services or AWS and Azure components.
Extensions
Develop and expand the IDE with your own components and IDE plugins, or find ready to use add-ons from our rich third-party ecosystem
RAD Server
Reduces the complexities of rapidly building and deploying a multi-tier turn-key enterprise REST API application server with Swagger support.
Are you ready to start using the best Windows app development tool?
If you’re looking to get started with Windows app development tools, or want to supercharge your team’s productivity, Delphi is the perfect solution. With powerful new features and quality improvements across all platforms, it’s never been easier to create high-quality applications that work seamlessly on any device. Ready to get started? Download a free trial of Delphi today and see for yourself how easy it is to build amazing apps with Delphi.
References
[1] https://learn.microsoft.com/en-us/windows/apps/winui
[2] https://en.wikipedia.org/wiki/File:Screenshot_of_WinForms_Designer_as_seen_in_Visual_Studio_2019.png
[3] https://github.com/microsoft/WindowsAppSDK/discussions/1615
[4] https://arstechnica.com/gaming/2016/03/tim-sweeney-to-microsoft-universal-windows-platform-can-should-must-and-will-die/
[5] https://news.xbox.com/en-us/2019/05/30/microsoft-approach-to-pc-gaming/
[6] https://learn.microsoft.com/en-us/windows/apps/design/basics/
Windows Forms, WPF или UWP и Как создать визуальный проект C#
На самом деле, холивар, плюс я мог не указать какие-то актуальные проблемы или указать уже решённые.
При работе на C# и ряде других языков, входящих в экосистему .NET, в настоящее время есть несколько подходов к написанию «приложений с интерфейсом» (то есть, имеющих форму — окно с интерфейсными компонентами Windows):
1. Windows Forms — классический UI-фреймворк, отрисовка выполняется с помощью библиотек Windows User32 и GDI+.
2. WPF (Windows Presentation Foundation) — современная подсистема для построения графических интерфейсов, основанная на использовании ля создания интерфейсов языка декларативной разметки XAML и отрисовке компонент с помощью DirectX.
3. UWP (Universal Windows Platform) платформа, впервые представленная в Windows 10. Цель — создание универсальных приложений, запускаемых на декстопе и мобильном устройстве без изменений в коде.
Преимущества Windows Forms:
- WYSIWYG-дизайнер форм;
- Компонентная архитектура;
- Поддержка невизуальных компонентов;
- Поддержка детерминированного уничтожения;
- Полная интеграция с базовыми библиотеками .NET;
- Нативные элементы управления идеально вписываются в тему Windows, потому что являются её частью;
- Экономное потребление системных ресурсов;
- При грамотном использовании компонентной модели рутинная работа может быть сведена к нулю, и программу с большим количеством однотипных форм можно написать за день.
Недостатки Windows Forms:
- Привязка данных только к свойствам и только по смене фокуса;
- При масштабировании экрана в новых Windows может «съехать» раскладка формы, технология была изначально не рассчитана на современные возможности масштабирования;
- В основе технологии лежат нативные элементы управления Windows, их внешний вид сложно изменить, и типовое приложение выглядит достаточно скромно, и для преодоления этого недостатка требуются сторонние библиотеки наподобие Infragistics или DevExpress;
- Есть вероятность потери большого количества работы при крахе дизайнера форм. Ошибки нередко возникают при работе со сторонними компонентами.
Преимущества WPF:
- При ошибке в работе дизайнера ничего фатального произойти не может, потому что внешний вид приложения описывается как xaml (основанный на xml язык разметки для приложений);
- Можно настроить внешний вид стандартных элементов управления практически как угодно, плюс разработать свои нестандартные элементы управления;
- Проблемы при масштабировании экрана в новых Windows возникают гораздо реже, чем при использовании Windows Forms;
- Привязка данных гибко настраивается;
- Поддержка анимации, звука, 3D графики.
Недостатки WPF:
- Писать xaml гораздо более трудоёмко, чем пользоваться дизайнером Windows Forms. Кроме того, декларативный код требует большей концентрации внимания и аккуратности при написании, а отлаживать его почти невозможно. В целом, архитектура технологии не располагает к быстрой разработке, сложнее автоматизировать рутину;
- Непредсказуемое поведение при изменении темы Windows. Теоретически, WPF подстраивается под тему Windows, но на практике её элементы управления могут выглядеть по-разному в зависимости от темы Windows, и всё равно не нативно;
- Ограниченная интеграция с базовыми библиотеками .NET Framework;
- Как следствие, отсутствует поддержка невизуальных компонентов и детерминированного уничтожения. Компонентная модель поддерживается лишь выборочно;
- Неудобная система задания расположения элементов управления через явные номера строк и столбцов в самом распространённом контейнере. При изменении во внешнем виде приложения нужно их исправлять во всех элементах управления;
- Постоянно что-нибудь масштабируется и в результате размывается — шрифты, растровые картинки. Проблема зависит от монитора, видеокарты и темы Windows;
- Использование рекомендуемого Microsoft паттерна MVVM (Model-View-ViewModel) приводит к раздуванию объёма исполняемого кода.
- Отсутствует диалог выбора директории из коробки;
- Отсутствует поддержка MDI из коробки. Поскольку это базовая функция практически в любом приложении, приходится либо делать самостоятельно, либо искать сторонние решения;
- Высокое потребление системных ресурсов.
UWP — похожая на WPF технология, к её преимуществам можно отнести:
- Интеграция с магазинами приложений;
- Возможность разрабатывать приложение параллельно под разные платформы (Windows, Android);
- Встроенная поддержка диалогов.
Недостатки UWP:
- Отсутствует возможность подключения к базе данных;
- Работает только в новых версиях Windows, начиная с 10.
По впечатлениям разработчиков, WPF быстрее работает на новых компьютерах, а Windows Forms на старых.
Можно сделать вывод, что типовые потребности в разработке стандартных приложений лучше закрывает Windows Forms. WPF имеет смысл использовать для специфических задач, требующих нестандартной векторной графики и не требующих хорошей совместимости программы с разными типами компьютеров. UWP имеет смысл использовать для разработки тонких клиентов популярных сервисов под разные платформы.
Типовой состав проекта Windows Forms: Visual Studio создаёт довольно много файлов, поэтому каждое приложение размещается в новой папке проекта. На рисунке показана типовая структура проекта с одной формой, а ниже в описано назначение основных файлов (пути указаны от открытой папки проекта на рисунке).
Папка проекта C# внутри папки решения
- ../ WindowsFormsApp1.sln где WindowsFormsApp1 – имя решения, в данном случае стандартное. Относится к категории группы проектов, объединенных в одно решение. Организует все элементы проекта (проектов) в одно общее решение
- Form1.cs содержит класс формы, которая по умолчанию запускается при старте приложения
- Form1.Designer.cs содержит определение компонентов формы, добавленных на форму в графическом дизайнере (графический дизайнер Windows Forms на данный момент официально доступен только в Visual Studio)
- WindowsFormsApp1.csproj стандартный файл проекта C#, который соответствует назанию проекта (по умолчанию названию каталога) и описывает все его настройки
- WindowsFormsApp1.csproj.user дополнительный файл проекта C#, который хранит специфичные для текущего пользователя настройки
- Program.cs определяет класс Program, который запускается при старте приложения и запускает форму Form1
- Form1.resx хранит ресурсы формы. Как правило, ресурсы используются для создания однообразных форм сразу для нескольких языковых культур
- app.config позволяет настроить способ, которым общеязыковая среда выполнения будет находить и загружать файлы сборки
- Properties (вложенная папка) организует хранение параметров для работы приложения
- ../packages (папка) хранит внешние библиотеки (пакеты), если таковые подключались. Данные об используемых в проекте пакетах в этом случае прописаны в файле packages.config
Обратите внимание, что при архивировании проекта пакеты папки, значки которых на рисунке вычеркнуты, можно предварительно удалить из папки проекта, чтобы уменьшить объём хранимого или пересылаемого архива.
Предполагается, что мы создали проект Windows Forms или Windows Forms App по следующему алгоритму:
1. Запустив Visual Studio, нажмём «Создание проекта», выберем язык и тип проекта, нажмём «Далее»:
Создание проекта C#, шаг 1
Заметим, что разница между двумя типами проектов «Приложение Windows Forms» состоит в том, что Windows Forms App использует технологию .net core, а Windows forms app .NET Framework, соответственно, технологию .net framework.
2. При необходимости поменяем имя проекта и решения, укажем целевую папку, включим опцию «Поместить решение и проект в одном каталоге», если проект будет единственным в решении, нажмём «Создать»:
Создание проекта C#, шаг 2
При макете окон по умолчанию мы получили следующую картину:
Окно проекта C# по умолчанию
С помощью перетаскивания мышью закрепив справа «Панель элементов» и окно «Свойства» получаем удобный для разработки несложных приложений интерфейс:
Удобный для разработки несложных приложений интерфейс
Основные элементы окна Visual Studio:
- Обозреватель решений позволяет наглядно увидеть структуру приложения и включённые в него или связанные с ним файлы, а также открыть их;
- Окно Конструктора или Кода, переключение между этими режимами делается первыми пунктами меню Вид (Код, Конструктор) или указанными в этом меню «горячими клавишами»; в режиме Конструктора мы создаём интерфейс приложения и обработчики его событий, в режиме Кода – пишем наполнение созданных функций;
- Панель элементов, позволяет добавить (перетащить) в окно Конструктора элементы интерфейса приложения;
- Окно Свойства позволяет изменить свойства объектов, выбранных в конструкторе, а также назначить обработчики для событий этих объектов. Обратите внимание на кнопки сортировки свойств (по категориям или по алфавиту), переключения между отображением свойств и событий, а также на область описания выбранного свойства или события внизу данного окна. Как правило, значения свойств можно вводить с клавиатуры или выбирать из предложенных списков, а для создания обработчика события достаточно выполнить двойной щелчок мышью на нужном событии из списка;
- В верхнем меню находятся списки выбора конфигурации приложения и кнопка сборки + запуска (с зелёным треугольником).
- При компиляции, сборке или отладке приложения в нижней части окна приложения появляются дополнительные сведения, а также сообщения об ошибках.
Этот материал подробнее и с парой примеров приложений, файл «Основы Windows Forms» PDF (707 Кб)
27.01.2023, 11:48 [2296 просмотров]
К этой статье пока нет комментариев, Ваш будет первым
Yes, mobile is the future of client applications, cross-platform is cool, web applications are amazing; but out there in the real world, there are still a ton of people who work all day with a Windows PC, and businesses that want PC applications in order to get their work done.
So when a business comes to you and says, we want a new Windows application to do this or that, and presuming they do not care about mobile or Macs or access over the internet but just want something that runs on their internal network, what framework do you choose?
Let us even assume that they all run Windows 10 so that UWP (Universal Windows Platform) is a realistic option.
If you want to code in .NET (which is a great choice for a Windows-only application, and with the possibility of migrating code to cross-platform via Xamarin’s compiler later), then you have three obvious choices:
Windows Forms
This is the framework for Windows desktop applications that was introduced at the same time as .NET itself, back in 2002. Of course it has been revised many times since. There was a big update in 2006 with .NET 2.0. That said, Microsoft intended it to be replaced by Windows Presentation Foundation (WPF, see below), so it has not been a focus of attention. In 2014, High DPI support was improved, with .NET 4.5.2, reflecting the fact that this ancient framework is still widely used.
Windows Forms is a nice wrapper around the Windows API, and easy to use in that it uses essentially X Y layout. In other words, you can think of your form as a grid of pixels with the position of your controls determined at design time by its size and coordinates. This is great if you are designing and running on the same PC, but not so good when you deploy to other PCs with different display settings. It does kind-of scale if you follow certain rules, but successful scaling in a Windows Forms application is often difficult to achieve, so users may suffer chopped-off controls and text, or just ugly screens. Read this carefully if you use Windows Forms. And then read about High DPI support, which was improved again in .NET Framework 4.7.
If you are writing a database application, you can generate datasets by drag and drop from the Server Explorer in Visual Studio and bind them to controls. I am not a fan of this database framework, which quickly gets convoluted, but you do not have to use it. However the ability to bind list and grid controls to any kind of .NET collection is fantastically useful.
Why is Windows Forms still in use? It is partly legacy and the fact that it is easier to maintain and enhance an existing application than to start again. It is also because, scaling issues aside, Windows Forms is reliable, well supported by both built-in and third-party controls, and easy to learn.
Windows Presentation Foundation
This was Microsoft’s second go at a GUI framework for .NET and in many respects a great improvement. It was introduced with .NET Framework 3.0 in 2006, part of the Vista wave of technology. Unlike Windows Forms, it is based on the DirectX graphics API, so great for multimedia and special effects. Scaling is built-in and based on layout managers. The underlying presentation language is based on XAML, an XML language. As with Windows Forms, there is deep support for binding data to controls.
Why would you not always use WPF rather than Windows Forms? The main issue is that the time you save on figuring out scaling is more than consumed by the time you spend on design. WPF is a designer-centric framework. It will repay your efforts, but if you just want to slap a couple of grids and a few buttons on a form to get a working business application, Windows Forms remains tempting.
Universal Windows Platform
Both Windows Forms and WPF are old, and Microsoft is pointing developers towards its Universal Windows Platform (UWP) instead. UWP is an evolution of the new application platform introduced in Windows 8 in 2012. If WPF was all about scaling and multimedia, the Windows 8 modern app platform is about touch support and Store-based deployment. The application model was also service based, the idea being that your app consumes services published over the internet. Until the Windows 10 Fall Creators Update, you could not use the .NET SQLClient to connect directly to a SQL Server database (you can now). The app platform became UWP with the launch of Windows 10 in 2015. UWP can use XAML for layout design, but it is not compatible with WPF.
Personally I have mixed feelings about UWP. Unfortunately it has suffered from Microsoft’s ever-changing development strategy. The Windows 8 app platform made sense to me as a way of bringing Windows into the tablet era and enabling applications that were more secure and more easily deployed, even if it tended to result in applications that were blocky and ugly. Microsoft then changed its mind about full-screen touch applications and came up with the UWP for Windows 10, where applications again run in a window, but with a new selling point: you could run your application on Windows Phone as well as desktop. Then the company canned Windows Phone, before UWP had properly launched, in effect deleting the “Universal” part of the platform.
UWP still offers Store delivery and isolation from other applications, better for security and stability. However there are a few things against it. First, users require Windows 10. Second, like WPF it is a designer-centric platform and not so good for running up quick business applications. Third, UWP apps behave differently from standard desktop applications, sometimes not in a good way.
I was using Microsoft’s bundled Photos application recently. I work a lot with images so this often pops up, as the default image viewer on Windows 10. I was not stressing it, but it crashed which, as is typical for a UWP app, means it just disappeared without any message or warning.
UWP will be three years old this summer, but I am not convinced that the platform is quite there yet. I find it hard to think of UWP apps that I love. The apps I know best are the built-in ones, Mail, Photos, Groove Music, Calculator, and I do not love any of them. Paint 3D is amazing but not my thing.
At the same time I do see the merits of UWP versus traditional Windows application deployment. The existence of the Desktop Bridge (formerly Project Centennial) means you can get many of those benefits while still using WPF or Windows Forms.
Closing thoughts
Perhaps something like Power Apps will render this discussion irrelevant before long. There are also other options for the desktop, such as Xamarin Forms if you still want to use .NET, or Electron for using web technologies for desktop applications.
Still, while it may seem surprising, even in 2018 I can think of reasons why you might use any of the above frameworks, even Windows Forms, for a business app targeting Windows.
WinUI (Windows UI Library) is the latest in a long line of UI frameworks from Microsoft for developing Windows software applications. You might be wondering why you would choose WinUI over the older frameworks that still exist and are supported by Microsoft.
Let’s look a little deeper into earlier Windows platforms to see how WinUI compares to its predecessors and why you might choose WinUI for your next desktop application.
Comparing WinUI to Earlier Frameworks
Over the past 30+ years, Microsoft has maintained a large number of frameworks for developing and distributing software for its own Windows operating system. We could go back to the beginning with Visual Basic 6 and ActiveX components, but those technologies are obsolete, so we will just look at the frameworks that are more relevant today. These include MFC, Windows Forms, WPF, and WinUI. We will also include UWP in our comparison because it serves as the direct predecessor to WinUI and offers some unique features and background to WinUI.
The table below provides a high-level overview of each framework.
There are several key differences between WinUI and earlier frameworks. In the sections that follow, we’ll dive a bit deeper into each framework.
MFC (Microsoft Foundation Class Library)
The Microsoft Foundation Class Library (MFC) uses Visual C++ and acts as an object-oriented wrapper over Win32 for the rapid development of native Windows applications. It works by providing class instantiation and dynamically translating data structures or objects to store, transmit, or reconstruct later. It also provides the code for basic input and output and managing windows as well as storing collections of menus and dialog boxes.
The MFC framework makes Visual C++ programming easy with a set of reusable classes to simplify Windows programming. It provides classes for objects used in basic programming, such as strings, files, and standard Windows API and data structures (like windows and controls).
Our legacy ActiveX controls, like VSFlexGrid and True DBGrid, can technically be used in MFC applications, but aside from these, ComponentOne does not provide any MFC UI components. The latest version is MFC 14.x (released in October 2024) and will be supported for years to come.
.NET WinForms (Windows Forms)
In 2002, Microsoft released WinForms along with the .NET Framework. WinForms offers reusable UI controls and functionality unique to the newer versions of Windows at the time, but, like MFC, it’s also over Win32. Windows Forms .NET applications are developed using Visual Studio with the help of visual designers. This enables drag-and-drop functionality and a preview of the application before compilation, which significantly simplifies building desktop applications.
After nearly two decades, WinForms development is going strong with .NET 9 and ComponentOne WinForms UI controls, continuously expanding the UI options available to developers. WinForms applications can be written with C# or VB.NET.
Ready to Get Started? Download ComponentOne Today!
WPF (Windows Presentation Foundation)
WPF (Windows Presentation Foundation) was released with .NET 3.0 in 2006 as a potential replacement for WinForms. It uses XAML (similar to XML) to define and separate the user interface from C# or VB.NET code.
WPF is built upon DirectX, a lower-level rendering engine that allows optimal performance on Windows. WinForms uses GDI+ (graphics device interface), which is a legacy graphics drawing library. WPF takes advantage of modern 2D and 3D graphics hardware, animations, styles, and media. It offers a similar drag-and-drop experience for developing user interfaces, though the design-time experience is not as complete as WinForms and often forces developers to work directly in XAML markup to fine-tune the interface.
Parts of Visual Studio itself are written in WPF.
UWP (Universal Windows Platform)
While apps built with MFC, WinForms, and WPF are called desktop or Win32 apps, UWP apps are called Universal Windows Apps, or sometimes, Windows Store apps. In 2012, Microsoft released Windows 8 and introduced two completely new application UI frameworks named WinJS and WinRT (Windows Runtime) XAML so that developers could write apps in either JavaScript or C# and XAML. However, the JavaScript arm didn’t last long, and by the time Windows 10 was released, the C# and XAML branch remained but was referred to as UWP for short.
Since UWP is not built on Win32, it only features a subset of full Windows functionality. It was designed to be lighter and more “modern”—think “tablet app” rather than a high-horsepower desktop application.
UWP uses XAML to define the user interface just like WPF, but for some reason, Microsoft gave up on delivering the same drag-and-drop design-time experience in Visual Studio. With UWP (and later WinUI), developers must write their entire UI by manually typing XAML. The application logic can be written with C# or C++.
The UWP framework uses Windows Runtime (WinRT) APIs to provide powerful UI features, and it’s distributed alongside Windows updates to take your application to the next level. UWP works by using a virtual registry and system files to avoid conflict with other apps.
One of the main drawbacks and the death knell of UWP was that it required users to update to the latest Windows version to access fixes, improvements, and new UI controls. This requirement was a bit of a bottleneck for users who could not constantly update to the latest version of Windows. Microsoft had to design a new framework, now known as WinUI, to solve this problem.
In 2024, Microsoft released an upgrade path for UWP apps to modernize and use the latest version of .NET. This appears to extend the life of UWP apps but does not serve as a long-term solution.
WinUI
WinUI, the latest Windows app framework for Windows 10 and 11, uses the Windows App SDK and WinUI 3.0. The community commonly refers to these apps as WinUI apps, though technically, UWP apps use WinUI 2.0, so it can be a bit confusing.
Unlike UWP, which is only compatible with Windows 10 devices, WinUI is backward-compatible with earlier versions of Windows 10 and 11. WinUI is decoupled from Windows, so updating is easier. For example, with WinUI 3.0, you can build and ship apps with new features without waiting for users to run the latest Windows update.
WinUI Benefits
Let’s explore some benefits of building apps with WinUI compared to other frameworks.
- Modern UI with Fluent Design: Compared to MFC, WinForms, and WPF, WinUI provides a modern, fluent design out of the box, so your application will feel up to date.
- Easy to Update: Unlike UWP, developers can use the latest WinUI controls without updating Windows since the app SDK is uncoupled from the Windows SDK.
- Publish Windows Store or Win32 apps: You get the best of both worlds as you can develop a modern, Windows Store-style application or a Win32 app that has the same capabilities as MFC, WinForms, and WPF.
- Backward Compatibility: WinUI provides backward compatibility with a wide range of Windows 10 versions. For example, users who aren’t on the latest version of Windows 10 can build and ship apps with new XAML features immediately after they are released.
- Support for JavaScript: With React Native support, you can create and distribute native Windows apps with WinUI developed using JavaScript components. Its features include automatically linking native modules, better-theming support, and a navigation menu.
- Uses XAML: Unlike MFC and WinForms, WinUI uses XAML to define the UI, which enables seamless styling, data binding, templating, and clear separation of UI from business logic.
- XAML Islands: You can use WinUI to create “XAML Islands,” incrementally adding WinUI elements to existing WPF, WinForms, or MFC applications, modernizing the UI without a complete rewrite.
- Scalability with .NET MAUI: By developing with .NET MAUI, you can create WinUI applications that scale instantly to mobile versions for Android, iOS, and even macOS.
WinUI Disadvantages
Although WinUI is an improvement over older frameworks, it does have some disadvantages.
- No Windows 7 Support: WinUI cannot run or be deployed on Windows 7. However, the Uno platform does add this support.
- No WYSIWYG Designer in Visual Studio: Without a user-friendly, drag-and-drop design surface, getting up and running can be more difficult.
- Less Mature: Compared to WinForms or WPF, the community and vendor-provided controls available for WinUI are much less. You can see the ComponentOne WinUI controls that are available today.
- Less Stable: Given that Microsoft keeps re-inventing the frameworks behind modern Windows apps, from WinJS and Windows 8 to UWP and WinUI, it would not be surprising if they take another sharp turn in the future. Many developers are concerned that the future is not clear.
- Can’t Deploy to Xbox: Unlike UWP, WinUI never received XBox support.
Ready to try it out? Download ComponentOne Today!
Conclusion
WinUI is the latest in a long line of UI frameworks by Microsoft. The core difference between WinUI and earlier frameworks is the access to fluent design and modern-looking UI controls without requiring an updated SDK. Although it has some disadvantages and an unclear future compared to older frameworks, many developers have switched to WinUI for its flexibility, backward compatibility, and cross-platform support through .NET MAUI.
If you are interested in WinUI, you can save development time with the ComponentOne WinUI & MAUI controls. Quickly add compact and flexible data grids, charts, reports, calendars, inputs, business intelligence dashboards, and other UI elements to your WinUI application to enhance user experience with familiar controls.
You can also check out what’s coming down the road in Microsoft’s WinUI roadmap.
WinUI 3.0 is the hot new framework for desktop application development. In this post we’ll try to answer the questions “What is WinUI 3.0?”, “How different it is from WPF, UWP and WinForms?” and ultimately “What is the best framework for developing desktop applications?”
With Microsoft introducing WinUI 3.0 and promising the new desktop application project called WinUI UWP is coming, the question of “which way I should use to build my desktop app?” becomes more and more relevant.
Many of you probably already know what UWP or WinUI is, but still in this post we will describe what WinUI and WinUI 3.0 are, what are the differences with existing MS desktop frameworks, and how to choose the best one for your needs:
Let’s try to answer to these questions:
- What is UWP?
- What is WinUI?
- What is WinUI 3.0?
- What is WinUI UWP?
- How is a WinUI UWP app different than exisiting UWP apps?
- Which of WinForms, WPF or WinUI UWP is better for my needs?
- How to create a WinUI UWP (using WinUI 3.0) app?
What is UWP?
UWP stands for Universal Windows Platform. Microsoft describes it by stating: Windows 10 introduces the Universal Windows Platform (UWP), which provides a common app platform on every device that runs Windows 10. The UWP core APIs are the same on all Windows devices.
So UWP has APIs that you as developer use to target all devices that support Windows 10. By doing that you can write your application once and deploy it on all Windows 10 supported devices like PC, tablets, HoloLens, etc.
UWP is distributed as part of Windows, so newer versions included fixes, improvements and new UI controls. But not everyone can afford the luxury of updating to the latest Windows version, so Microsoft decided that it would be better if the UI library is decoupled from Windows. Thus, WinUI was born. You can think of it as an API that was extracted from UWP so it is easier to update it.
What is WinUI?
Microsoft describes WinUI as: Windows UI Library: the latest Windows 10 native controls and Fluent styles for your applications. Currently there are two versions of WinUI — version 2.0 and WinUI 3.0.
The current official version WinUI 2.x can be used to create UWP store applications. With features like XAML Islands you can include WinUI components in your existing desktop applications, but the process is not so straightforward at this point.
What is WinUI 3.0?
WinUI 3.0 is a major update of WinUI 2.0 that will greatly expand the scope of WinUI to include the full Windows 10 native UI platform, which will now be fully decoupled from the UWP SDK. What this means is that you will be able to create a desktop application using WinUI 3.0 much like using WPF or WinForms now.
As of this writing the only supported Windows version is Windows 10 (excluding enterprises who paid for Windows 7 extended support).
When WinUI 3.0 becomes official .NET developers will have several options to create desktop applications:
- Creating WinUI 3.0 desktop application
- Creating WPF desktop application
- Creating WinForms desktop application
- Creating MFC desktop application
- Creating Win32 desktop application
What is WinUI UWP?
This is a UWP app referencing and using Win UI 3.0 components, allowing us to create performant UWP with beautiful UI following the Fluent design system. The new project type WinUI UWP is available in VS 2019 Preview.
How is it Different than Simple UWP App?
Basically, it is a UWP app with preadded references to the Microsoft.UI assembly (WinUI3.0).
But, the main difference is that WinUI 3.0 APIs are in the Microsoft.UI namespace instead of the Windows.UI namespace, so you might need to update the namespaces when copying and pasting sample code. Similarly, libraries and components using UI controls from Windows.UI.Xaml are not compatible with WinUI 3.0 and must be updated to Microsoft.UI.Xaml.
So, WinForms, WPF or the New Modern Desktop App (WinUI UWP) ?
Let’s first say some words about WinForms versus the other options
This is the framework for Windows desktop applications that was introduced at the same time as .NET itself, back in 2002. As such:
+ This is stable desktop framework.
+ A lot of resources available.
+ A lot of 3rd party libraries such as Telerik UI for WinForms are also available.
+ Perhaps the biggest advantage of WinForms is that it easy to learn.
+ You can create the whole layout with the drag and drop functionality in VS.
— Not so good when it comes to customization of the UI and building a modern look and feel.
— Not very good DPI support (unless you are using 3rd party library that provides support for that like Telerik UI for WinForms)
Windows Forms allows developers to build complex desktop apps, but if you need a modern look and feel, high DPI support and flexibility you may consider other options as WPF and UWP (these include exisiting UWP apps and future WinUI UWP)
However, you still have options when it comes to good looking UI — try the modern themes that Telerik UI for WinForms has to offer.
It is important also to note that WinForms apps can run on operating systems that UWP can’t.
And as WPF and UWP allow us to create more modern UI and have a lot of advantages, let’s take a closer look at them both. WinUI is major part of building UI with UWP and WinUI 3.0 is the future of WinUI, so we will look directly at the difference between WPF and UWP apps built with WinUI 3.0.
How to Choose Between WPF and WinUI 3.0 UWP Apps?
Both of these frameworks have a lot of advantages like:
- A separate language to describe the UI layout (XAML).
- Powerful data binding allows a cleaner separation of UI and domain logic.
- Command and Model-View-ViewModel Pattern
- Data/control templates – a much cleaner way than anything Windows Forms can offer.
- Styles – cool and simple. Its so easy to style all your inputs in an application to have the same look and feel.
- UI virtualization – I’ve got grids with 100K rows, ticking off a moving market. Performance would be dreadful if it wasn’t for UI visualization which comes for free.
- 3D support.
- Both platforms are based on Vector graphic UI based on DirectX
Now, let’s see the differences.
How is WPF Better than a WinUI 3.0 App?
- First of all – it is a more stable framework proven by time.
- There are also a lot of resources and 3rd party components like Telerik UI for WPF. This 3rd party library adds to the framework more than 140 components and 20 modern themes including Fluent-like styling.
- It also runs on other version on Windows lower than Windows 10.
While in UWP, the app cannot overcome some restrictions. Examples include:
- FileSystem access is restricted to libraries (e.g. Document library)
- Resource access is defined by App Capabilities. This way a user sees what the App can do (e.g. use location service).
- Starting of processes / services is forbidden.
- Interprocess communication is forbidden.
And… if you a F# fan you can build your desktop app with WPF.
How is a WinUI UWP App Better than WinForms and WPF?
Well, in short — it gives a modern look and feel to the applications with the Fluent Design pattern, and it is built based on C++ so it performance optimized compared to WPF apps. So, here are the benefits of the new WinUI apps coming:
- A modern look and feel. Fluent Design System — this allows you to build modern desktop applications. This is one of the biggest advantages of the new desktop apps. More intuitive and engaging UI.
- All versions of Windows 10
- Runs on PC, Notebook, Tablet, Phone, Xbox, IoT, Surface Hub
- Optimized for touch
- Optimized for memory usage and performance
- More interactive — built animations
- Managed code in WPF apps is in general slower than native code and requires more memory. UWP Apps written in C# or VB are compiled to .NET Native. This way the app has almost the high-performance of a native app.
So, as WinForms and WPF already have a lot resources in this post we will focus on how to create our fist WinUI UWP app.
How to Try WinUI 3.0 and Create a WinUI UWP App?
As this is still in preview creating such a project doesn’t come built-in in VS. Here are the needed prerequisites:
- Install VS 2019 Preview 15.4 or above
- Check whether .NET Desktop Development and Universal Windows Platform development workloads are selected
- Fill a Microsoft form on the following link and after you are done you will receive a link to VS gallery — https://aka.ms/WinUI3AlphaAccess
- Download and install the VSX extension
Now after we are ready, we can create a new WinUI UWP project.
Now, we can see that the project itself contains a reference to the Microsoft.WinUI assembly.
You can see that the namespace for the WinUI 3.0 is already there and we can simply add WinUI components. For example Rating, AcryicBrush and PlaneProjection.
<
StackPanel
Margin
=
"105"
Background
=
"{ThemeResource SystemControlAcrylicElementBrush}"
Height
=
"400"
Width
=
"400"
>
<
StackPanel.Projection
>
<
PlaneProjection
RotationX
=
"-35"
RotationY
=
"-35"
RotationZ
=
"15"
/>
</
StackPanel.Projection
>
<
RatingControl
/>
<
TextBlock
Margin
=
"10"
>Type Something Below</
TextBlock
>
<
TextBox
Margin
=
"10"
></
TextBox
>
<
Button
Margin
=
"10"
Content
=
"Click"
Width
=
"100"
/>
</
StackPanel
>
And here is where your imagination or business case comes to the scene – start exploring and share your experience!
Resources:
More about WinUI 3.0 — https://docs.microsoft.com/en-us/uwp/toolkits/winui3/
Offcial WinUI site — https://microsoft.github.io/microsoft-ui-xaml/
Summary
Microsoft currently gives us more than one technology to build a desktop app, but if you want to focus on a modern look and feel, trying WinUI 3.0 is the right thing to do. However after that whatever the technology you choose — Telerik UI is here to support you! Do not hesitate to write us if the component or feature that you need is not available and stay tuned for all new staff in Telerik and KendoUI for R2 2020!