Windows forms на linux

Although WinForms may be “dead”, it does have one trick up its sleeve that WPF doesn’t, and that is you can run WinForms apps on mono. Here’s a simple guide to running a Windows Forms application on Ubuntu

Step 1 — Install Mono

Open a terminal window, and make sure everything is up to date with the following commands:

sudo apt-get update
sudo apt-get upgrade

Now you can install mono with the following command:

sudo apt-get install mono-complete

Step 2 — Create an Application

Now we need to create our C# source file. You can use any text editor you like, but if like me you aren’t familiar with Linux text editors like vi or emacs, gedit is a simple notepad-like application which is easy to use. Launch it with the following command: (the ampersand at the end tells the terminal not to wait for gedit to close before letting us continue)

gedit wf.cs &

Now let’s create a very simple application:

using System;
using System.Windows.Forms;

public class Program
{
    [STAThread]
    public static void Main()
    {
        var f = new Form();
        f.Text = "Hello World";
        Application.Run(f);
    }
}

Step 3 — Compile and Run

Now we’re ready to compile. The C# compiler in mono is gmcs. We’ll need to tell it we’re referencing the Windows Forms DLL:

gmcs wf.cs -r:System.Windows.Forms.dll

To run the application, simply call mono, passing in the executable:

mono wf.exe

And that’s all there is to it! We have a WinForms app running on Linux.

Although mono doesn’t support everything in WinForms, you can use most standard controls, so you can easily add further UI elements:

Taking it Further

Obviously writing applications by hand like this is a bit cumbersome, but there is an IDE you can use for Linux called monodevelop. You install it like this:

sudo-apt-get install monodevelop

This then gives you a nice editing environment, allowing you to debug, and manage project references (you’d usually add System.Windows.Forms and System.Drawing). Unfortunately it doesn’t offer a WinForms designer – for desktop apps it prefers you to use GTK#. Nevertheless, it’s a nice free IDE allowing you to experiment with getting your existing Windows Forms applications working cross-platform on Linux. (It seems this will also work on OS X with mono installed but I don’t have a Mac so I haven’t tried it out)

image

In this episode I am going to talk about using graphical applications in Mono. The graphical framework to use would be Windows Forms.

Introduction and Background

I took more than necessary break in posting the content and articles for Ubuntu programming in C#. Anyways, I am continuing from the same place where I left and, as already taught that we were at the final stages of sharing the guide for programming C# on Ubuntu; which can be thought of as a Linux environment. The previous posts can be found easily on my blog and on some of the networks that I support.

Previously, we had already talked about NuGet gallery packages, cryptographic helpers and much more. Whereas, in this post I am going to walk you people through using Windows Forms framework on Mono framework.

Windows Forms framework

Now, who doesn’t know Windows Forms framework in today’s world? If you have ever wanted to or have developed the C# programs or .NET applications. Then you are already familiar with Windows Forms application. Windows Forms is an old framework with graphical capabilities, and has been in the game for a more than a decade by now! It has started to get replaced by Windows Presentation Foundation, but nonetheless, it is still very popular and is being used widely by many software developers and many software development companies are still relying on it.

There are many benefits of using Windows Forms in your regular development teams,

  1. It supports graphics, not just the CPU and RAM processing.
  2. It can be used with resources for localization support is excellent.
  3. Provides a better way for drawing graphics on canvas.
  4. Event handling, delegate generation.
  5. Asynchronous programming patterns.
  6. Good data binding support provided.

I am going to provide you with some good references that you can use to learn more about Windows Forms, if sadly, you have no idea about the Windows Forms framework. However, one thing is for granted. Using Windows Forms is one of the easiest ways of building the graphical applications in ,NET environment.

References

Follow the following links and learn more about Windows Forms:

  1. Windows Forms
  2. Getting Started with Windows Forms
  3. Windows Forms Overview

Graphical applications in Mono Project

We have until now, discussed and learnt how to build small programs and some very common applications that use special kind of algorithms, such as cryptographic helpers which can be used to encrypt and decrypt the data in Ubuntu using C#. Now, until this we haven’t covered graphical applications development in Mono, because that is where this framework lags behind.  So, in this post we would like to learn how to build applications with graphical capabilities too. But, first, let’s talk about the frameworks provided in Mono Project itself.

  1. GTK#
    • Which is a similar one to the GTK+ that C++ programmers have. This is a graphical toolkit that compiles down to the native code generation. It supports the native look and feel and can be used. But, it is somewhat difficult to learn!
      Banshee1

      Figure 1: GTK# control application example.

  2. Windows Forms
    • This is the topic that we are going to cover in this post.
  3. Other tools?
    • Not yet, Mono Project is not ready to implement other frameworks yet.

The thing is, Mono Project doesn’t have an excellent UI designer as we have in Visual Studio.

Screenshot (3062)

Figure 2: Visual Studio UI Designer.

In Mono Project and Xamarin Studio, you are not provided with the similar tools until now. However, the designer is just the wrapper around the back-end code available. Xamarin Studio does have a good designer, but that works with GTK# tools and controls only. Not in the case of Windows Forms.

Applying a quick hack!

If you have ever programmed for Windows Forms, then you would know that Windows Forms is actually a bunch of objects with many fields and properties, which run and work to render the graphics on the screen. The same is applicable here. We would be using the codes to render the stuff on the screen. Basically, everything that you have on the screen is a field in the backend class, such as “Button”, “TextBox”, “Label” etc. These are all going to be used, but, we are going to write the codes for this, instead of having a designer build them up for us.

Building the UI with Windows Forms

So, I hope using the hack is clear to you, after all, it is not a hack it is the actual way in which Windows Forms applications are constructed, built and executed. Only difference is that on Windows we also get to use the UI designer. In case of Mono Project, we would have to craft the UI with our own codes and then re-implement it if there is a changing to be performed on the screen later. Thus, putting it simply, we are going to implement it the hard way since there is no, “Drag-and-drop” method here.

To get started, you need to understand that a Windows Forms application is a C# application too. So, only thing to understand is C# language itself and the .NET framework. We are going to use the same concepts of .NET framework and then implement the same concepts to Mono to get our graphical applications ready.

Create project — Any type

I had chosen to build this application on the top of Console application. You can select other types too. But, my recommendation is using the Console application.

Screenshot (3064)

Figure 3: Selecting the console project as the type.

Enter the names and details and create the project.

Screenshot (3065)

Figure 4: Entering the details for the project.

At this moment, you will be at the same stage where you were in the beginning of this module, and the previous ones. You will have an empty project, that only renders, “Hello world”. That is the start, from here we will continue to build the larger and complex stuff.

Screenshot (3066)

Figure 5: Hello world!

This program is the default program that every time we were shown. Now, we need to add the graphics to the console. That’s simple. All we need to do is… Read the next section. ;-)

Adding graphics to the console

Adding the graphics to the console is pretty much simple, you just need to do the trick as:

  1. Include the System.Windows.Forms namespace to the project.
  2. Include the System.Drawing namespace to the project.
  3. Import the packages to your source code.
  4. Write the code yourself; since we do not have the designer.
  5. Run the program, and you will see the program start up.

But, I am going to show you how to do that in a minute or two. But first, let us understand why Windows Forms can be build using the code itself. The thing is, the Windows Forms applications are started on a thread, the thread gets the graphics objects and bitmaps which are rendered on the screen later. The objects are simply instances of the classes, for instance of Button class. These are all passed to the Application object, and they are executed, upon execution they render the graphics on the screen.

Another thing to understand and note is that Windows Forms uses System.Drawing to draw the native code in Mono. Mono targets the objects using the assemblies provided in System.Drawing namespace, and then renders the objects on the screen. At the moment, Mono supports on Win32 theme for the objects. In the end of this post, you will see how your objects are going to look. Remember, the objects are instances… :-)

Open the references and add the references to System.Windows.Forms and System.Drawing namespaces,

Screenshot (3067)

Figure 6: Initially references are like this.

Screenshot (3068)

Figure 7: Adding the references to the namespaces. 

Now that we have everything set up, we can now continue to create a new Windows Form. This method is not similar to what we had in the previous IDEs, like Visual Studio. Instead, we are going to just mimic having a Windows Form.

Adding the Windows Form to your project

First thing to note is that there is no way of creating the form by itself in Mono Project. So, we are going to create a new object, and then we are going to turn it into the form and then render it using the main function. That’s just similar to what happens in Visual Studio too. You create the form, whose graphics are rendered separately in a designer, and the codefile is generated separately. Visual Studio maintains everything for you, which is why you do not feel anything different.

Step 1:

Create a new class, name it what you like, I chose MyForm and then write the following code to it.

using System;
using System.Windows.Forms;

namespace GraphicalApp
{
    public class MyForm : Form
    {
        // No properties.

        public MyForm ()
        {
            // Default constructor
        }

        // No functions.
    }
}

This is it. This is out, Windows Form now.

Step 2:

Before running the program, you also need to make sure that the main function now calls this form to be executed in the application too.

// In the references
using System.Windows.Forms;

// In the main function
Application.Run(new MyForm());

Now, run the project and you will (should!) see the following window with no controls, but with a graphical notation and rendering.

Figure 8: Sample empty Windows Form application.

This shows that our project is ready to accept the objects for graphical components. We can now write the code for the objects that we need to render. For example and for the sake of simplicity I would like to create a sample form that renders the form, which would ask me about my name and then would greet me once I click on the button.

All of these are core C# programming concepts and this has nothing to do with the Windows Forms or any other fundamental concept. Instead, these are very simple and yet easy features of C# programming language itself.

Step 3:

Anyways, to update, we can just update the MyForm class and write the code that we would need to have in order to render the form.

using System;
using System.Windows.Forms;
using System.Drawing;

namespace GraphicalApp
{
    public class MyForm : Form
    {
        // Properties.
        private Label label;
        private TextBox myName;
        private Button btn;

        public MyForm ()
        {
            // Call the function to render the objects.
            Text = "Windows Forms app";

            this.Size = new Size(300, 350);
            render();
        }

        private void render() {
            label = new Label { Text = "Your name: ", Location = new Point(10, 35) };
            myName = new TextBox { Location = new Point(10, 60), Width = 150 };
            btn = new Button { Text = "Submit", Location = new Point(10, 100) };
            btn.Click += Btn_Click; // Handle the event.

            // Attach these objects to the graphics window.
            this.Controls.Add(label);
            this.Controls.Add(myName);
            this.Controls.Add(btn);
        }

        // Handler
        void Btn_Click (object sender, EventArgs e)
        {
            MessageBox.Show ("Hello, " + myName.Text + "!");
        }
    }
}

Now again run the program, and you will see the following graphical application being rendered on the screen for you!

Figure 9: This is the Windows Forms application on Ubuntu. 

Figure 10: Entering the data and seeing that it works. 

Now, if you have been an old geek for Microsoft and Windows, then you would know that this style existed for decades in Windows environment. This style was typically adopted for Windows programming with C++, especially Win32 and then later C# was introduced and they had a different style; create a WPF app and look for yourself!

This is how Mono does the trick for Windows Forms. It does support Windows Forms and can use the same power of .NET framework to provide the similar ways to build the graphical applications for Linux environment. The benefit is that, you can now execute, build and run these graphical applications on Windows, Linux (every distro that supports Mono runtime) and Mac OS X. What more could you ask for? :-)

Points of Interest

In this post, i have walked you through different stages of building the graphical applications on Ubuntu using C# in Mono Project. The benefit of using graphical applications is that you can do more in less area, because “A picture worth a thousand words!”. Windows Forms is a framework that has been widely used by programmers of C# language and is still being used. If you can port your applications of Windows Forms to other platforms, it would be much better.

In this post, I have shown you how to do that. You can port your Windows Forms application, by porting the code for that application project, and then building it under Mono compilers.

The Mono runtime however, only supports Win32 theme for controls and however, provides a versatile amount of features, incredibly, they support all the new features of Windows Forms too. Which means, you can work around with:

  1. Graphics
  2. Multimedia
  3. Content management
  4. Data binding
  5. Event handling
  6. Asynchronous programming

And much more. There are more posts about Mono framework to come, but we are getting closer to having the guide completed and to be ready as a complete guide for “Programming C# on Linux”; or Ubuntu, what-ever you prefer. :-)

Run WinForms Apps for Windows CE on Linux

Cross-Platform Compatibility for Legacy Applications

Are you looking for a way to run Windows Forms applications originally built for WindowsCE on a Linux environment? Mono provides a powerful and flexible solution to bridge the gap, enabling you to execute .NET applications seamlessly.

F&S also provides libraries for interface interaction, so you can even call I²C, SPI and UART from your WinForms app running on Linux!

Why Use Mono for WindowsCE Apps?

  • Cross-Platform Support – Run .NET WinForms applications on Linux without requiring a Windows runtime.
  • Extend the Lifecycle of Legacy Software – Keep your existing applications operational even as Windows CE support declines.
  • Cost-Effective Migration – Avoid expensive rewrites by leveraging Mono’s compatibility with the .NET framework.
  • Open-Source & Customizable – Adapt and optimize your solution for embedded and industrial environments.

Why not use Microsoft .NET for Linux?

Microsoft offers .NET for Linux. Problem with this version is the missing support for WinForms or WPF. So if your application simply uses .NET without graphics, .NET for Microsoft is our recommendation.

How It Works

Mono is an open-source implementation of the .NET Framework that supports running Windows Forms applications outside of the Windows ecosystem. With the right configuration, it can execute applications built for WindowsCE, offering an alternative runtime on Linux-based systems. The additional libraries from F&S ensure that even the calls to hardware interfaces can stay the same in Linux as in WindowsCE.

Get Started

Your application should already implement the APIs provided by F&S if you need to interact with the hardware interfaces I²C and SPI (NativeI2C.dll and NativeSPI-V1.dll). We also provide them for Linux systems, so your software can interact with these interfaces without extensive changes in the code base. What needs to be changed in code however, are the device names. For example I2C2: must be called with /dev/i2c-2 in Linux and SPI1: could be /dev/spidev0.0, but this depends on your hardware and pin connections.

Next, Mono must be installed on your Linux system. For the F&S Yocto releases, this can be achieved by adding the meta-mono layer (https://git.yoctoproject.org/meta-mono/about/) to your build. If you have your new Linux system installed on your board, you still need to prepare Mono by adding a library provided by F&S (called libfs_dotnet_io_api.so.0.1), which replaces the WinCE-library coredll.dll. [HF1] This library “translates” your interface calls from Windows to Linux commands.

Copy your Windows-executable to the board, alongside the Linux-specific APIs NativeI2C.dll and NativeSPI-V1.dll. Then run your application:

mono [path/to/your/app.exe]

You can find the code for the APIs and the library on GitHub:

https://github.com/FSEmbedded/NativeI2C_Linux

https://github.com/FSEmbedded/NativeSPI-V1_Linux

https://github.com/FSEmbedded/dotnet_linux_IO_API

Following are some screenshots of a demo application by F&S running on two different efusA9X. The Code is also available on GitHub: https://github.com/FSEmbedded/WinForms_On_Linux_InterfaceDemo

On one of these is Windows CE 2013 installed, the other one uses the latest Yocto-release from F&S (fsimx6sx-Y2024.12) with additional Mono installed. This software can interact with I²C, SPI and UART on both Operating Systems without any changes in the code.

System.Windows.Forms for .Net Core running on Windows and Linux

This is a early stage and experimental port of Mono’s System.Windows.Forms and a few additional libraries to .Net 6.0+. This allows Winforms code to run on both Windows and Linux (and possibly MacOS in the future).

Rather then porting Mono’s implementation of System.Drawing to .Net 6.0 I ported Mono’s System.Windows.Forms onto System.Drawing.Common. Note that on Linux you will need some native libraries.

Even though this is highly experimental and unsupported it does work (at least for me).

Builds are available via Nuget from the package Core.System.Windows.Forms or at https://www.nuget.org/packages/Core.System.Windows.Forms/.

As of Alpha 4 this targets .Net 6.0 instead of .Net Core 3.1.

A Demo on my Raspberry Pi 4, built and running on the Pi using .Net Core 3.1.

Platform Requirements

Windows — None known

Linux — Several native libraries, at least libx11 (libx11-dev on Ubuntu) and libgdiplus (libgdiplus on Ubuntu)

Mac — Not currently working. The Mono code that this is based on was 32 bit only. .Net Core requires 64 bit so until that is done this will not work.

Samples

There are three samples: SimpleTest (which uses my .Net Core Winforms), SimpleTest.NetCore (which uses the official .Net Core Winforms) and SimpleTest.NetFX which uses Net Framework. This also shows how to use the same source code with all three different platforms as the code is added as a link to the NetCore and NetFX projects. This way you can use the officially supported and nice looking Winforms on Windows.

To test this on Linux simply dotnet run in the SimpleTest folder.

More samples are coming soon TM. This will include more complex forms and more demonstrations of using the different libraries for different platforms.

I tested the SimpleTest example on Windows, Raspbian Buster and Ubuntu 20.04 using .Net Core 3.1 Release.

Future Work

Unknown right now. I will likely add more samples and fix issues as I go. If Mono adds support for Mac 64 bit I will port that over.

I will add better Linux documentation as I have time.

License

The Mono code is under the MIT license (https://github.com/mono/mono/blob/master/LICENSE). My contributions are under the MIT license as well.

WinForms, short for Windows Forms, is a popular UI framework developed by Microsoft for building desktop applications on the Windows operating system. While WinForms has been traditionally associated with Windows development, there is a growing demand for running WinForms applications on Linux. This guide will explore the possibilities and options for WinForms development on Linux.

Running WinForms Applications on Linux

Running WinForms applications on Linux is made possible through various compatibility layers and tools. One of the most popular tools for running WinForms applications on Linux is Wine. Wine is a compatibility layer that allows Windows applications to run on Linux by translating Windows API calls into POSIX calls. While not perfect, Wine has made significant progress in running WinForms applications on Linux.

Another option for running WinForms applications on Linux is using Mono. Mono is an open-source implementation of the .NET framework that allows developers to build and run .NET applications on non-Windows platforms, including Linux. Mono includes support for WinForms, allowing developers to create cross-platform applications with a native look and feel.

Developing WinForms Applications for Linux

While running WinForms applications on Linux is possible, developing WinForms applications specifically for Linux requires some additional considerations. When developing WinForms applications for Linux, it is essential to keep in mind the differences in user interface design preferences between Windows and Linux users. Linux users generally prefer applications that follow the native Linux UI conventions, so adapting your WinForms application to match the Linux UI guidelines is crucial for a better user experience.

Another consideration when developing WinForms applications for Linux is testing and debugging. While tools like Wine and Mono can help run WinForms applications on Linux, it is essential to test your application on a Linux system to ensure it works correctly. Additionally, debugging issues that arise on Linux may require different tools and techniques compared to Windows development.

Optimizing WinForms Applications for Linux

To optimize WinForms applications for Linux, there are several best practices to keep in mind. Firstly, avoid using Windows-specific features and APIs that may not be supported on Linux. Instead, stick to cross-platform libraries and frameworks that work seamlessly on both Windows and Linux.

Additionally, consider using platform-specific code to customize the behavior of your WinForms application on Linux. By detecting the platform at runtime, you can make adjustments to the user interface and functionality to better fit the Linux environment. This approach ensures that your application looks and performs well on Linux while still maintaining compatibility with Windows.

Conclusion

While WinForms development has been primarily focused on Windows, there are ways to run and develop WinForms applications on Linux. By leveraging tools like Wine and Mono, developers can bring their WinForms applications to the Linux platform and reach a wider audience. With careful consideration of user interface design, testing, and optimization, WinForms applications can deliver a seamless experience on Linux.

Are you interested in exploring WinForms development on Linux? Reach out to us for expert guidance and support!

#WinForms #Linux #WinFormsDevelopment #CrossPlatformDevelopment #Wine #Mono

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Производители планшетов на windows
  • Почему не устанавливается шрифт на windows 10
  • Takeown f c windows system32 termsrv dll a
  • Windows socket error 10055
  • Активация windows server 2019 kmsauto