Skip to content

Frontend using WinForms

AlmantasK edited this page Apr 11, 2021 · 7 revisions

Backend vs Frontend vs Fullstack

If you open recruitment sites, you will see most posts usually falling under 3 categories:

  • Backend
  • Frontend
  • Fullstack

The 3 categories refer to what you will be focusing on as a programmer.

Backend- puts a heavy focus on business logic, often without changing how things look. Console application is also considered fully backend- because you don't care how do things look like- you just dump output to the console.

Frontend- is the opposite. Your focus is to make user experience good, applications easy to use, accessible. You will try to make things pretty and cool. It has another name- UI.

Fullstack- you will do it all. There is a nice balance between both back and front ends.

Client Side

Client is the end a user will interact with. Other than its visuals, we need to figure out how to call the other end- backend, how to translate backend calls back and forth. All that involves in making a client side is a responsibility of a full stack developer.

The problem

Client often changes, but should that affect all the code behind we tried to carefully piece together? Of course not! Therefore, looks should not impact how code behind it works.

The Solution: 2 Layers

A layer in programming can have different forms. In .NET, it is usually a project. Therefore, it is usually a good idea to seperate presentation from business logic.

Historically, the first 2 layers was called 2-tier application. Though it is not the same as the 2 layers I am referring to. 2-tier = client + database. 2 layers is backend and frontend separation.

Let's try to go through a typical flow of implementing 2 layer application and thus separating client and logic ends.

Empty Solution

Create an empty solution. In a new project window, type Solution and select the option that says Blank Solution. Call it after your application name, for example RecipeConverter.

Blank Solution

First Project- Application

You should strive to solve the problem first and visualize the solution next. Unless you have strict requirements on how visual part should look like- do not start from it.

The best kind of pure backend project is a class library. Class libraries are supposed to be containers of logic, without any visual parts in it. Therefore, you cannot run a class library project- the idea is to call it from an executable project type.

In .NET, you now have 4 options when it comes to choosing a project type:

  • .NET Framework - old, windows-only
  • .NET - latest, multiplatform
  • .NET Core- previous, multiplatform
  • .NET Standard- all is built on this, works mostly with everything (post 4.6.1 .NET).

If you don't have any platform-specific needs, use .NET Standard for your business logic implementation. That is exactly what we will be choosing.

Right click on the solution, select "add.." -> "new project".

Add new Project

Type Class Library. And Name the project after your solution name suffixing it with .App (stands for application logic).

Class Library Project

Second Project- Client

If you are making some executable, consider to always split the presentation from logic. Though console application is considered to be not frontend related, it still is the most simple client, because it does visualize something.

What visualization you add is up to you. This lesson is about winforms, so we will add winforms project.

Name the proejct after your solution name suffixing it with .Client.

WinForms Project

Link Client and Application Logic Projects

The setup we want to make is that the client project refer to the application project.

Client-Application

In .NET, in order to consume logic from another project we need to add a reference to that project.

Expand RecipeConverter.Client project, right click on "Dependencies" and select "Add Project Reference" from the list select RecipeConverter.App project.

Project Reference

The Key Point

This might seem a lot of work. However, by spending just several minutes we separated visual part from logical. It is great to be a in a habbit of not relying on one from the other, until you really need that, because it gives you room for making choices of what integrates how.

Would you like to convert winforms client into a console? Maybe there is a need for a website? Maybe you need all 3? All of it is fine now- because the core application is still the same and the only thing you will need to figure out how to visualize things, rather than how to rewrite the business logic so that it works in other environments. Business logic will not change, presentation can change and such design is based on that assumption. It's okay for business logic changes to impact the visuals, but not the other way round.

Separation in projects design prevents you from making mistakes where you forget yourself and accidentally use pieces of console or WinForms or other UI(user interface)-specific thing when all you really do is process something. If you want to visualize something that you calcualte, don't embed it in a function. Keep the frontend stupid- use backend output as-is and just assign it in the right place.

A Look at WinForms

All in this paragraph will be solely on winforms. It is okay not to know these things as this is the only time we will be covering it.

Winforms in general are mostly used for internal tooling, made repidly just for developer's convenience. You will not be able to make off-the-shelf kind-of applications using winforms, because they simply rely too much on Windows OS and is not designed for anything else. That said, it's good for introducing concepts, for learning purposes and therefore was our pick to get started with client side.

Template

Winforms template introduces just 2 files:

  • Forms1.cs - visual window
  • Program.cs - bootstrap the first window

Form

Form is a window. For every new window in your applciation you will have to create a new form.

Empty-Form

Controls

Tool Box

By default, opening a form should reveal a toolbox, however if it doesn't, go to "View" and select "Toolbox". It will open the Toolbox window which I recommend that you pin.

Toolbox

Expand Common Winforms Control because that's what we will be using.

From here, you can drag and drop control onto the form. Individual element can be resized, but if you would like to change other properties, you will need to open the properties window.

A control is a visual element in a form. It is a class which has certain traits for user interaction or visual representation.

TextBox

Is the most basic one- used for editing text. Usually meant just for a single or a few words.

TextBox

RichTexBox

Like TextBox, but is resizable and offers to store a full string, supports scrolling. Also keeps the formatting of text which was pasted in it (keeps links, bodling, etc).

RichTexBox

Button

Can be clicked and calls an action on click.

Button

Label

Is just text which, unlike TextBox, is not intended for editing.

Label

RadioButton

A group of two or more round buttons which can be toggled on or off. Only one radio button in a group can be toggled on. Toggling one button turns off others.

Empty-Form

GroupBox

Is one way to group multiple control. Used for shared sizing or related visualization. For example, great for putting multiple RadioButton controls, so that toggling one will de-toggle the others.

In the image above with RadioButtons they are actually place in a GroupBox.

MessageBox

Is a box which has an text section and one option- Ok.

MessageBox

OpenFileDialog

It is very common to read a file from a winform. In order to do it in a Windows-native way, you will need to use OpenFileDialog class. It opens a file browser through which you can pick a file.

For example, in order to read file contents from OpenFileDialog you can:

static string ReadFile()
{
    // Create a browser object (prep for using)
    using (OpenFileDialog openFileDialog = new OpenFileDialog())
    {
        // Show dialog and wait till selection is confirmed
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            // The dialog returns a stream
            var stream = openFileDialog.OpenFile();
            // For meaningful work, it's convenient to convert to a StreamReader
            using (StreamReader reader = new StreamReader(stream))
            {
                // Read the contents of the file
                return reader.ReadToEnd();
            }
        }

    }

    // In case a cancel or close was clicked
    return string.Empty;
}

WinForms Designer

Open Form1.cs file. It will open the WinForms design window. Here, you can drag-and-drop visual elements from the toolbox and create UI without much of know-how.

Control Properties

In order to modify the properties of, let's say a button, right click it. Let's change the name of our button to: "Convert". It's also a good idea to give a meaningful name to the control itself- instead of Button1, let's renamed it to ConvertButton.

Button-Properties

Anchor

There are many properties, one of the more interesting ones is an anchor. It defines how control moves and changes size when the parent window changes its size.

For example, here we defined a control which will expand with the parent moved to the following directions: up, down, left.

Anchor

Using it is a must if our form can change in size.

Events

Winforms uses events to handle user interaction. For example, if a user click a button, Clicked event is fired. How to handle those events?

Double click a button. It will create an event handler called YourButton_Click(). Inside that method you can write code which will be executed when the button is clicked.

For example:

private void HelpButton_Click(object sender, EventArgs e)
{
    MessageBox.Show("This is just a tutorial");
}

And that's really all you need to know for now in order to get started with Winforms! Enjoy!

Last Words on Winforms

WinForms is considered to be a little bit of a legacy thing. It is windows-only, created over 20 years ago. However, if you are not making big things, if you just want to make a quick application for yourself or the team, if you just want to try a new thing out and get an understand of a frontend is- it is great. Winforms is the most simple way of making applications with some client.

If you want to make on-the-shelf kind-of applications, consider other options like: UWP, WPF, Xamarin Forms, MAUI (all of those are in .NET ecosystem).

Howework

Take the recipe app done in lesson 4 and finish it implementing what is required in International Recipe Converter problem.

Did You Understand the Topic?

  • What is the difference between backend and frontend?
  • What does it mean to do fullstack development?
  • What is UI?
  • Why risks does having both frontend and backend in the same project impose?
  • What is Winforms?
  • What is an event and how to handle them in Winforms?
  • Why do we need an anchor?
  • Should you avoid WinForms?
Clone this wiki locally