Windows Forms program download how to add. Programming in .NET Framework. Tests for LoginPresenter

Golovna / Corisna information

Today I want to tell you how to create a C++ Windows Forms project in the Visual Studio 2013 IDE. On the right, in what, starting with VS 2012, from the list of projects that can be created, the Windows Forms Addendum item was removed. I'm talking about those in C ++, you can create such a project in C # by selecting the option in the distribution of projects that are being created. However, the fact that such a project cannot be selected from the list does not speak of those that cannot be created. For myself, I want to expand on this article.

The first thing you need to do is launch Visual Studio. As soon as VS was launched, it is sequentially pressed File\u003e Create\u003e Project

Afterwards, it will be requested to choose the type of the project. We need to select the Visual C++ extension CLR extension and select Empty CLR project.

If the project is created, in the browser, the solution is clicked with the right mouse button for the created project. In the context menu, which has appeared, it is sequentially selected Add > Create Element and in the menu, which has appeared, in the UI section, it is selected Windows Forms Form

If the form is submitted, the MyForm.cpp file is selected in the browser solution. In front of you new tab with a single row of code:

#include "MyForm.h"

For this file, we need to add the next code:

Using namespace System; using namespace System::Windows::Forms; void Main(array ^ args) ( Application::EnableVisualStyles(); Application::SetCompatibleTextRenderingDefault(false); Project1::MyForm form; Application::Run(%form); )

Let's hear from the authorities of the project. Selected pіdrozdil System split Builder and in a row Subsystem from the menu select Windows (/SUBSYSTEM:WINDOWS) and click Start.

Without curtailing the project’s authority, let’s move on to the subdivision of Dodatkovo and in a row entry point write Main and after that we press the key OK.
On which project will be completed. To edit the current look of the form, go to the MyForm.h [Constructor] tab by clicking on the MyForm.h file in the Solution Browser.

Have a nice day!
Model-View-Presenter - present a custom design template. From the first glance, everything looks simple: є model (Model), like to revenge the entire business logic on the screen; View / Submission (View), which you know, how to display those other data; The representative (Presenter), which is a lucky one - reacts to the subdivision of the coristuvacha in the View, changing the Model, and navpaki.
Folding begins, if the number of forms in the project becomes greater for one.
The article looks at:
- Trochy theory;
- burning problems implementation of MVP (passive view zocrema) under Windows Forms;
- features of the implementation of transitions between forms and the transfer of parameters, modal windows;
- IoC container affiliation to the Dependency Injection - DI template (and Constructor Injection itself);
- specific features of testing MVP programs (for NUnit and NSubstitute tests);
- everything should be applied to the example of a mini-project and to be motivated but to get it right.
The article is stuck:
- Zastosuvannya template Adapter (Adapter);
- Simple implementation of the Application Controller template.
For whom is this article?
The main rank for retailers-pochatkivtsiv on Windows Forms, like chuli, but they didn’t try it, or they tried it, but they didn’t. Wanting to sing, deyakіyi zastosovnі for WPF, and navіt for web development.

Problem statement

Think up a simple task - implement 3 screens:
1) authorization screen;
2) head screen;
3) modal screen to change the name of the koristuvach.
Guilty to visit schos on kshtalt tsyogo:

Trochy theory

MVP, like a godfather, MVC (Model-View-Controller) of inventions for the sake of clarity, the division of business logic into the way of visualization.

On the Internet, you can see impersonal MVP implementations. According to the method of delivery of data for submission, they can be divided into 3 categories:
- Passive View: View to eliminate the minimal logic of displaying primitive data (rows, numbers), the Presenter will take care of the decision;
- Presentation Model: View can transmit not only primitive data, but also business objects;
- Supervising Controller: View knows about the presence of the model and takes data from it.

Let's take a look at the Passive View modification. Let's describe the main drawings:
- Data interface (IView), which is the best agreement for data display;
- Appearance - a specific implementation of IView, as if it can display itself in a specific interface (Windows Forms, WPF or open the console) and do not know anything about those who use it. Have different forms;
- Model - gives a business logic to the business logic (apply: access to the database, repositories, services). Maybe it is presented in a different class or again, the interface and implementation;
- a representative to send a message to the Submission through the interface (IView), which requires him to subscribe to your submission, zdiisnyuє simple validation (verification) of data input; also to take revenge on the model or interface, transferring data to it from View and requesting an update.

Typical implementation of a representative

public class Presenter ( private readonly IView _view; private readonly IService _service; public Presenter( IView view, IService service) ( _view = view; _service = service; _view.UserIdChanged += () => UpdateUserInfo(); ) private void ) ( var user = _service.GetUser(_view.UserId); _view.Username = user.Username; _view.Age = user.Age; ) )


What pluses give us a minimal connection of classes (various interfaces, sub)?
1. Allows you to freely change the logic of any component, without making a decision.
2. Great opportunities for unit-testing. TDD shanuvalniks can get their hands on the grip.
Let's do it!

How to organize projects?

Let's think that the solution is formed from 4 projects:
- DomainModel - revenge services and all repositories, in a word - model;
- Presentation - to avenge the logic of the report, so as to lie in the sight of a visual manifestation, tobto. all Representatives, interfaces Appearance and other base classes;
- UI - Windows Forms addendum, more forms (implementation of interfaces Appearance) and launch logic;
- Tests - unit tests.

What to write in Main()?

The standard implementation of running a Windows Forms program looks like this:

Private static void Main() ( Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm());
Ale mi did it, so that the Representatives cherubate the Appearances, he would like to, so that the code would look like this:

Private static void Main() ( Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var presenter = new LoginPresenter(new LoginForm(), new LoginService()); // Dependency Injection presenter.Run(); )
Let's try to implement the first screen:

Basic interfaces

// general methods of all appearances public interface IView ( void Show(); void Close(); ) // contract, which representative will interact with the form public interface ILoginView: IView ( string Username ( get; ) string Password ( get; ); ) event Action Login; // pod_ya "koristuvach tries to log in" void ShowError(string errorMessage); ) public interface IPresenter ( void Run(); ) // stupid authorization service public interface - Successful authorization, otherwise false )


tribute

public class LoginPresenter: IPresenter ( private readonly ILoginView _view; private readonly ILoginService _service; public LoginPresenter(ILoginView view, ILoginService service) ( _view = view; _service = service; _view.Login += () view .Password); ) public void Run () ( _view.Show(); ) private void Login(string username, string password) ( if (username == null) throw new null) throw new ArgumentNullException("password"); var user = new User(Name = username, Password = password); if (!_service.Login(user)) else ( // Successful authorization, launching the head screen (?) ) ) )


Create a form and implement it in the ILoginView interface, it doesn't matter how you write the ILoginService implementation. The following is less than one feature:

Public partial class LoginForm: Form, ILoginView ( // ... public new void Show() ( Application.Run(this); ) )
This is the spell to allow our add-on to start, display the form, and after closing the form, correctly complete the program. Let's turn around until then.

Will there be trials?

From the moment the representative (LoginPresenter) was written, it is possible to immediately perform yoga-unit-testing, not implementing any forms, any services.
For writing tests, I'm a contributor to the NUnit and NSubstitute libraries (a library for creating stub classes behind their interfaces, mock).

Tests for LoginPresenter

Public class LoginPresenterTests ( private ILoginView _view; public void SetUp() ( _view = Substitute.For (); // stub for the view var service = Substitute.For (); // stub for the service service.Login(Arg.Any ()) // no longer log in admin/password .Returns(info => info.Arg ().Name == "admin" && info.Arg ().Password == "password"); var presenter = new LoginPresenter(_view, service); presenter.Run(); ) public void InvalidUser() ( _view.Username.Returns("Vladimir"); _view.Password.Returns("VladimirPass"); _view.Login += Raise.Event (); _view.Received().ShowError(Arg.Any ()); // This method is responsible for calling the text of the pardon ) public void ValidUser() ( _view.Username.Returns("admin"); _view.Password.Returns("password"); _view.Login += Raise.Event (); _view.DidNotReceive().ShowError(Arg.Any ()); // and in my vipadka everything is OK))


Tests dosit bad, as long as the program itself. Ale, so chi іnakshe stinks successfully passed.

Who and how to launch another screen with the parameter?

As you can remember, I did not write the correct code for successful authorization. How can I launch another screen? First of all, it falls to the thought:

// LoginPresenter: login successful var mainPresenter = New MainPresenter(new MainForm()); mainPresenter.Run(user);
Alemy realized that the representatives did not know anything about the manifestation, the Crimea of ​​their interfaces. What is work?
The Application Controller pattern comes to the rescue (implementation is simplified), in the middle of which there is an IoC container, which you know, how to take the object of implementation behind the interface.
The Controller is passed to the skin Representative by a constructor parameter (new DI) and implements approximately the following methods:

Public interface IApplicationController ( IApplicationController RegisterView () where TImplementation: class, TView where TView: IView; IApplicationController RegisterService () de TImplementation: class, TService; void Run () where TPresenter: class, IPresenter; )
After a little refactoring, the launch of the program would look like this:

Private static void Main() ( Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // all fallbacks are now registered in one location: var controller = new ApplicationController(new LightInjectAdapder()) .RegisterView ().RegisterService ().RegisterView (); controller.Run (); }
A couple of words about the new ApplicationController(new LightInjectAdapder()) . As an IoC container, I hacked the LightInject library, but not directly, but through an adapter (Adapter pattern), so if you need to change the container to a different one, I could write a different adapter and not change the logic of the controller. All methods, which are victorious, are in most IoC-libraries, folded and not guilty.
An additional IPresenter interface is implemented, which is less likely that the Run method accepts a parameter. We will gradually decrease in the view of the new one, similarly to the first screen.
Now, not without pride, we launch another screen, passing the authorized koristuvach there:

Controller.Run (user); View.Close();

You can't just take and close the form.

One of the underwater stones in a row View.Close() , after which the first form was closed, and at the same time, an addition from it. On the right, Application.Run(Form) runs the standard Windows wakeup loop and looks at the passed form as the program's main form. This is due to the fact that the program hangs ExitThread on the Form.Closed sub, that calls the program to close after the form closes.
There are a number of ways to get around this problem, one of them is to change the method: Application.Run (ApplicationContext), then override the power of ApplicationContext.MainForm. Transfer to the form context is implemented for the help of the Program Controller, in which the ApplicationContext object (instance) is registered and then submitted to the form constructor (I start DI) at the start of the Representative. The methods for displaying the first two screens now look like this:

// LoginForm public new void Show() ( _context.MainForm = this; Application.Run(_context); ) // MainForm public new void Show() ( _context.MainForm = this; base.Show(); )

Modal window

The implementation of the modal window does not mean difficulties. On the "Change Name" button, Controller.Run is ticked (user). The only way to display forms in others is not headline, that form is not needed for display ApplicationContext:

Public new void Show() ( ShowDialog(); )
As much as it is necessary to recognize the difference, the method is not necessary to change, since the Form class already has implementations.

Well, they screwed it up ... How is it now CE vikoristati?

Now, if the frame is ready, the addition of a new form will lead to such short cuts:
  1. We write the interface of the Appearance, the interface of the Model (as required).
  2. It is realizable by the Representative, prima facie virishivshi, so that we will in the new transfer this data as a model.
  3. [Optional] We write a test for the Representative, we will change our minds, everything is fine.
  4. [Optional] Implementable Model and test for it.
  5. We give the form and implement the interface of the Appearance.
Changing the IoC container to your loved one is the way to implement a simple IContainer interface with an adapter class.

You can pick up a demo project from

  1. https://metanit.com/sharp/windowsforms/1.1.php

    Introduction to Windows Forms

    For the creation of graphical interfaces for the help of the .NET platform, different technologies- Window Forms, WPF, Windows Store programs (for Windows 8/8.1/10). However, the most simple and handy dossier platform is Window Forms or Forms. Danish help put as a metadata of understanding the principles of the creation of graphical interfaces for the additional WinForms technology and the work of the main elements of management.

    Created by graphic software
    To create a graphic project, we need the Visual Studio development environment. Since the version of Visual Studio 2013 is the most expanded so far, I’ll tweet for your help free version given medium Visual Studio Community 2013 Yaku can be found on the side https://www.visualstudio.com/en-us/products/visual-studio-community-vs.aspx.

    After installing the middleware and all its components, launch Visual Studio and create a graphics program project. For which, in the menu, select the File item (File), and in the submenu, select New -> Project (Create -> Project). The last thing we see before us is the dialogue window of the creation of a new project:

    The left column selects Windows Desktop, and the central part of the middle project types selects the type Windows Form Application and for a lady, I’m like I’m in the field below. For example, we call yoga helloapp. The next thing is pressed OK.

    After Visual Studio opens the project from the files created behind the lock:

    Most of the scope of Visual Studio is occupied by a graphic designer, who can take the shape of a future program. For the time being, it's empty and there is no more than the heading Form1. On the right you can find the solution/project files - Solution Explorer. There you can find all the files related to our addendum, including the files of the form Form1.cs.

    At the bottom, the right-hander is known as the window of authority - Properties. Since at this moment I have chosen the form as an element of control, then in which field the authorities appear, tied with the form.

    Now we know the power of the form Text and change its meaning to be-yak else:

    In this way, we changed the title of the form. Now transferable to the field is a key element, for example, a button. For which we know in the left part of Visual Studio the Toolbox tab (Toolbox). Click on this tab, and we will see a panel with elements, we can transfer the stars to the form for any other element:

    We know the middle elements of the i button, having loaded її in the mouse’s kazіvnik, we transfer it to the form:

    Tse is a visual part. Now let's get down to programming. Let me add the simplest code of my C#, a kind of activating and pushing buttons. For whomever I am guilty, go to the code file, which is the connection from this form. Since we do not have a code file to view, we can click on the form with the right mouse button and in the View Code menu (View the code file):

    However, we will speed it up in a different way, so as not to write too much code. Hover the mouse pointer at the button and click on the lower clicks. We automatically consume the code file Form1.cs, which looks like this:

    Using System;

    using System.ComponentModel;
    using System.Data;
    vicorist System.Drawing;
    using System.Linq;
    using System.Text;

    using System.Windows.Forms;

    Namespace HelloApp
    {

    {
    Public Form1()
    {
    InitializeComponent();
    }


    {

    }
    }
    }
    Dodamo displaying a notification after pressing the button, changing the code in the following order:

    Using System;
    vicorist System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    vicorist System.Drawing;
    using System.Linq;
    using System.Text;
    vicorist System.Threading.Tasks;
    using System.Windows.Forms;

    Namespace HelloApp
    {
    public partial class Form1: Form
    {
    Public Form1()
    {
    InitializeComponent();
    }

    Private void button1_Click(object sender, EventArgs e)
    {
    MessageBox.Show("Hi");
    }
    }
    }
    Launching the program
    To run the program in boot mode, press the F5 key or the green arrow on the Visual Studio panel. The next time our form starts up with the button itself. And if we press the button on the form, then we will be shown a reminder about vaping.

    After launching the program, the studio compiles yoga from the file from the extension exe. Know dani file you can, go to the project folder and move it to the bin/Debug or bin/Release directory

    Having looked briefly at the creation of a graphic supplement to the project, we can move on to an overview of the main components and, of course, forms.

  2. https://metanit.com/sharp/windowsforms/2.1.php

    Robot with forms
    Fundamentals of Forms

    Zovnіshnіy vglyad programs us overimportantly through forms. Forms are the main blocks of life. The stench put on a container for various elements of keruvannya. And the mechanism of subdivision allows the elements of the form to introduce coristuvacha, and, in such a manner, interact with coristuvacha.

    When opening a project in Visual Studio graphic editor We can use the visual part of the form - that part, as we can after the launch of the program and where the elements are transferred from the control panel. But in truth, the form takes on a hard functional, which is made up of methods, authorities, and other things. Let's take a look at the main power forms.

    If we run the program, then one empty form will appear. Protest such a simple project from an empty form with few components:

    Irrespective of those that my Bachimo only form, but the starting point for entering the graphic program of the Program class, arranging the files Program.cs:

    Using System;
    vicorist System.Collections.Generic;
    using System.Linq;
    vicorist System.Threading.Tasks;
    using System.Windows.Forms;

    Namespace HelloApp
    {
    static class Program
    {
    static void Main()
    {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
    }
    }
    }
    The program will start this class first, then we'll use Application.Run(new Form1()) to run the Form1 form for help. If we want to change the starting form as an addendum to another class, then we need to change Form1 to a different class of the form.

    The form itself is foldable behind a zm_st. Won subdivided into low components. So, the structure of the project has a file Form1.Designer.cs, which looks something like this:

    Namespace HelloApp
    {
    partial class Form1
    {
    ///


    /// Required designer variable.
    ///

    ///


    /// Clean up any resources being used.
    ///

    /// true if managed resources should be disposed; otherwise, false.

    {

    {
    components.dispose();
    }
    base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    ///


    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    ///


    {
    this.SuspendLayout();
    // Form1



    this.Name = "Form1";
    this.Text = "Hello world!";
    this.ResumeLayout(false);

    }
    }
    Here the form class Form1 is debunked, because it can have two methods: Dispose(), which takes the role of the object's destructor, and InitializeComponent(), which sets the initial values ​​of the form's powers.

    When adding elements, for example, buttons, their descriptions are also added to the file.

    Ale, in practice, we rarely z_shtovhuvatimemosya with this class, that stinks vikonuє in the main design functions - the installation of the authorities of objects, the installation of changes.

    Another file - Form1.resx- Save resources form. As a rule, the resources are victorious for the creation of single-mansion forms at the same time for a number of modern crops.

    І important file - Form1.cs, which is simply called Form1 in the structure of the project, to replace the code or the program logic of the form:

    Using System;
    vicorist System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    vicorist System.Drawing;
    using System.Linq;
    using System.Text;
    vicorist System.Threading.Tasks;
    using System.Windows.Forms;

    Namespace HelloApp
    {
    public partial class Form1: Form
    {
    Public Form1()
    {
    InitializeComponent();
    }
    }
    }
    For the caption here, there is only a form constructor, in which the InitializeComponent () method is simply called, there is a designer file Form1.Designer.cs. Same with the file mi and more pracyuvatimemo.

  3. https://metanit.com/sharp/windowsforms/2.2.php

    The main dominance of forms

    For the help of a special window Properties (Power), the right-handed Visual Studio gives us a handy interface for handling the power of the element:

    The greatness of these powers is poured into the visual form. Let's go after the main authorities:

    • Name: set it to the form - more precisely, the name of the class, which falls into the class Form
    • BackColor: indicate the color of the background of the form. Pressing on the power of power, we can choose the color that suits us from the list of suggested colors or the palette of colors
    • BackgroundImage: display on the background image of the form
    • BackgroundImageLayout: renders as an image, set in the BackgroundImage power, to appear on the form.
    • ControlBox: Specifies whether the form menu is displayed. AT to this particular type under the menu, the menu of the most important level is understood, where the program icon, the title of the form, as well as the minimization button, form that cross are found. If the power can be false, then we don’t need any icons, no cross, for the help of which the form will sound
    • Cursor: sets the type of the cursor that is typed on the form
    • Enabled: If power can be set to false, you can't accept text input, so you can't click on buttons, enter text in text fields, and so on.
    • Font: set the font for all forms and all the places on it. Prote, having set your own font for the elements of the form, we can redefine yoga
    • ForeColor: font color on the form
    • FormBorderStyle: Specifies how the header row should be displayed between the form. Restoring power to None can be created old look supplements of a fair shape
    • HelpButton: indicate whether the button for finalizing the form is displayed
    • Icon: set the icon of the form
    • Location: set the position relative to the top left corner of the screen, so the StartPosition power is set to Manual
    • MaximizeBox: specify whether the maximize window button in the form header will be available
    • MinimizeBox: specify whether the window minimization button will be available
    • MaximumSize: sets the maximum size of the form
    • MinimumSize: sets the minimum size of the form
    • Opacity: set the transparency of the form
    • Size: choose the cob rozmіr form
    • StartPosition: indicate the start position, which form will appear on the screen
    • Text: sets the title of the form
    • TopMost: if power can be set to true, the form will always appear on top of other windows
    • Visible: if the form is visible, if we want to attach the form to the corystuvache, then we can set this power to false
    • WindowState: Specify which form should be rebooted at startup: Normal, Maximized, or Minimized
    Programming of authorities
    For the help of the importance of power in the power of power, we can change the formal appearance of the form to our own judgment, and all those same we can create dynamically in the code. Let's move on to the code, for which we right-click the mouse on the form and select it in the View Code context menu. We have a code file in front of us Form1.cs. Change yoga like this:

    Using System;
    vicorist System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    vicorist System.Drawing;
    using System.Linq;
    using System.Text;
    vicorist System.Threading.Tasks;
    using System.Windows.Forms;

    Namespace HelloApp
    {
    public partial class Form1: Form
    {
    Public Form1()
    {
    InitializeComponent();
    Text = "Hello World!";
    this.BackColor = Color.Aquamarine;
    this.Width = 250;
    this.Height = 250;
    }
    }
    }

    In this way, we have improved the kіlka of authority in the form of the image: heading, background color, width and height. When changing the form constructor, you need to check that the code is supposed to go after the call to the InitializeComponent() method, so all the power settings here are changed to the next method.

    Installed expanded forms
    To set the size of the form, you can change the power such as Width/Height or Size. Width/Height take numeric values, like a pointed butt. When setting dimensions via the Size power, we need to assign the power to the object of the Size type:

    This.Size = New Size(200,150);
    The Size object is filled in the constructor with a numerical value for setting the width and height.

    Pochatkove roztashuvannya forms
    More often than not, the formation of the form is restored for additional power StartPosition, as you can take one of the following values:

    • Manual: The position of the form depends on the authority of the Location
    • CenterScreen: The position of the form at the center of the screen
    • WindowsDefaultLocation: The position of the form on the screen is determined by the Windows system, and the size is determined by the power Size
    • WindowsDefaultBounds: The initial position and size of the form on the screen is set by the Windows system
    • CenterParent: The position of the form is set at the center of the Batkivsky window
    All values ​​are moved to the FormStartPosition box, so, for example, put the form in the center of the screen, we need to write it like this:

    This.StartPosition = FormStartPosition.CenterScreen;
    Background ta colori form
    To set the color as the background of the form, so for the font, we need to highlight the color value that is stored in the Color structure:

    This.BackColor = Color.Aquamarine;
    this.ForeColor = Color.Red;
    In addition, we can set the background of the image in the background of the authorities BackgroundImage, drawing it in the image of the authorities or code, indicating the path to the image:

    This.BackgroundImage = Image.FromFile("C:\Users\Eugene\Pictures\3332.jpg");
    In order to properly improve the need for us to display the background image, we need to win the power of the BackgroundImageLayout, so you can take one of the following values:

    • None: The image moves to the upper left corner of the form and saves its cob value
    • Tile: The image is placed on the form in the form of a mosaic
    • Center: Image of stitching in the center of the form
    • Stretch: Image stretches to size without maintaining proportions
    • Zoom: The image expands to fit the shape to save proportions
    For example, let's expand the shape in the center of the screen:

    This.StartPosition = FormStartPosition.CenterScreen;

  4. https://metanit.com/sharp/windowsforms/2.3.php

    Adding forms. Interaction between forms

    To add one more form to the project, right-click on the project in the Solution Explorer window and select Add(Add)->Windows Form...

    Damo new form yakes im'ya, for example, Form2.cs:

    Otzhe, our project has been given a form to a friend. Now we'll try to create an interplay between two forms. Let's say that the first form is pressed on the button and the other form is clicked. First, add a button to the first form Form1 and click on the button to move to the file code. Otzhe, we can use it as a tool for pushing the button, which is created behind the lock after the pushing on the button:


    {

    }
    Now dodamo to the new code wiki of another form. We have another form called Form2, so we create an object of this class, and then for this display on the screen we click the Show method:

    Private void button1_Click(object sender, EventArgs e)
    {
    Form2 newForm = new Form2();
    newForm.Show();
    }
    Now zrobimo navpaki - another form has stuck into the pepper. For the time being, the other form does not know about the basis of the first. To fix it, you need another form to transfer information about the first form. For whom it is faster by transferring the request to the form from the constructor.

    Then, let's go to another form and go to the її code - right-click on the form and select View Code. As long as the wine is empty, it is not enough to take revenge on the constructor. Oskіlki C# podtrimu rebinding methods, we can create some methods and constructors different parameters that fallow in the situation viklikati one of them. Again, change the file to the code of another form for the attack:

    Using System;
    vicorist System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    vicorist System.Drawing;
    using System.Linq;
    using System.Text;
    vicorist System.Threading.Tasks;
    using System.Windows.Forms;

    Namespace HelloApp
    {
    public partial class Form2: Form
    {
    Public Form2()
    {
    InitializeComponent();
    }

    Public Form2(Form1 f)
    {
    InitializeComponent();
    f.BackColor = Color.Yellow;
    }
    }
    }
    In fact, little ones have added here a new public Form2(Form1 f) constructor, in which case we need to change the form and set it to the same color. Now let's move on to the code of the first form, demi called out to a friend the form of that change yogo on the offensive:

    Private void button1_Click(object sender, EventArgs e)
    {
    Form2 newForm = new Form2(this);
    newForm.Show();
    }
    Shards in this type of keyword this represent sending to the current object - the Form1 object, then when another form is created, it will be taken away by the first form.

    Now, after pressing on the button, we will create a different form, so as to change the color of the first form.

    We can also create objects that flow form:

    Private void button1_Click(object sender, EventArgs e)
    {
    Form1 newForm1 = new Form1();
    newForm1.Show();
    Form2 newForm2 = new Form2(newForm1);
    newForm2.Show();
    }
    When working with dekilcom, you need to check with forms that one of them is the head one, as it is launched first in the Program.cs file. As soon as a couple of forms are opened in us at once, then when the head is closed, the whole program is closed, and at the same time all other forms are with it.

  5. https://metanit.com/sharp/windowsforms/2.4.php

    Podії Windows Forms. Submit forms

    For interaction with Windows Forms, there is a sub-mechanism. Podії in Windows Forms represent the standard podії in C#, which only get stuck to the visual components and subordered by the same rules as in C#. But there are still some peculiarities in Windows Forms creation.

    For WinForms, there is a standard set of inputs, some of the best for all visual components. Okremі elementi add their podії, but the principles of work with them will be similar. To look at all the subelements of an element, we need to select the element from the graphic designer field and go to the sub tab on the form panel. For example, sub forms:

    To add a sample file, you can simply click on the empty field with the instruction to name the input, and then Visual Studio will automatically generate the sample copy. For example, press for the creation of a sample for the sub Load:

    І tse field will be displayed by naming the method of the sampler under Load. For promotions, the wine is called Form1_Load.

    Let's move on to the Form1.cs file, let's also auto-generate the Form1_Load method:


    {
    Public Form1()
    {
    InitializeComponent();
    }


    {

    }
    }
    І in case of dermal entanglement form, use the code in the form Form1_Load.

    As a rule, most collectors of various visual components have two parameters: sender - the object that initiated the sub, the argument that collects information about the sub (in this EventArgs e).

    Ale tse lisher obrobnik. To add a workbook created in such a rank, go through the Form1.Designer.cs file:

    Namespace HelloApp
    {
    partial class Form1
    {
    private System.ComponentModel.IContainer components = null;

    Protected override void Dispose(bool disposing)
    {
    if (disposing && (components != null))
    {
    components.dispose();
    }
    base.Dispose(disposing);
    }
    private void InitializeComponent()
    {
    this.SuspendLayout();

    This.AutoScaleDimensions = New System.Drawing.SizeF(6F, 13F);
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
    this.ClientSize = New System.Drawing.Size(284, 261);
    this.Name = "Form1";
    // Adding a brewer
    this.Load += New System.EventHandler(this.Form1_Load);
    this.ResumeLayout(false);
    }
    }
    }
    To add a quiz, the standard C# syntax is used: this.Load += System.EventHandler(this.Form1_Load)

    Therefore, if we want to see the creations in a similar way, we need not only to see the method with the form code in Form1.cs, but also to add the finder to this file.

    For example, we can add the details of the sub and programmatically, for example, in the form constructor:

    Using System;
    vicorist System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    vicorist System.Drawing;
    using System.Linq;
    using System.Text;
    vicorist System.Threading.Tasks;
    using System.Windows.Forms;

    Namespace HelloApp
    {
    public partial class Form1: Form
    {
    Public Form1()
    {
    InitializeComponent();
    this.Load += LoadEvent;
    }

    Private void Form1_Load(object sender, EventArgs e)
    {
    }

    Private void LoadEvent(object sender, EventArgs e)
    {

    }
    }
    }
    Krim before the created Form1_Load workbook, here is also the addition of another form workbook: this.Load += LoadEvent;, which will set a new color background.

  6. https://metanit.com/sharp/windowsforms/2.5.php

    A creation of rectangular shapes. Close form

    Behind the lock, Windows Forms are straight forward. Prote mi we can create and indirectly dovilni forms. For whom the power is won Region. As the meaning of it is the object of the same name class Region.

    When the non-rectangular forms are combined, they sound, the interforms do not vikorate, the shards of the cordon are given by the Region object. To use between forms, you need to set the form's FormBorderStyle authority to None.

    And one more aspect, which needs to be protected, poling in displaced, closed, maximizing and minimizing forms. So in this way, like in the primary form, we cannot press on the cross to close the form, we cannot move it to a new place. That is why it is necessary to designate for this program logic.

    Otzhe, let's move on to the form code and change it with the coming rank:

    Using System;
    vicorist System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    vicorist System.Drawing;
    using System.Linq;
    using System.Text;
    vicorist System.Threading.Tasks;
    using System.Windows.Forms;

    Namespace HelloApp
    {
    public partial class Form1: Form
    {
    Point moveStart; // point to move

    Public Form1()
    {
    InitializeComponent();
    this.FormBorderStyle = FormBorderStyle.None;
    this.BackColor = Color.Yellow;
    button1.Text = "Close";
    }

    Private void button1_Click(object sender, EventArgs e)
    {
    this.Close();
    }

    Private void Form1_Load(object sender, EventArgs e)
    {
    System.Drawing.Drawing2D.GraphicsPath myPath = new System.Drawing.Drawing2D.GraphicsPath();
    // create an ellipse with a height and a width of the form
    myPath.AddEllipse(0, 0, this.Width, this.Height);
    // create for the help elіpsu form that area, as you want to bachiti
    Region myRegion = new Region(myPath);
    // Set the visible area
    this.Region = myRegion;
    }

    Private void Form1_MouseDown(object sender, MouseEventArgs e)
    {

    if (e.Button == MouseButtons.Left)
    {
    moveStart = new Point(e.X, e.Y);
    }
    }

    Private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
    // the left button of the mouse is pressed
    if ((e.Button & MouseButtons.Left) != 0)
    {
    // take a new form position point
    Point deltaPos = new Point(e.X - moveStart.X, e.Y - moveStart.Y);
    // set form position
    this.Location = new Point(this.Location.X + deltaPos.X,
    this.Location.Y + deltaPos.Y);
    }
    }
    }
    }

    The creation of the form area is checked in the Form1_Load subproject. For the creation of the area, a graphic path is drawn - an object of the System.Drawing.Drawing2D.GraphicsPath class, to which the elips is added. The graphic way allows you to create a figure, be it a form, that, if we want a form at the sight of a sea star, then it is simply necessary to fix the victorious graphic way with a proper rank.

    To close the form in the form by pressing the button1_Click button, the form is closed by the program: this.Close()

    For moving the form, two sub-forms are processed - pressing the button of the mouse and moving the button of the mouse.

  7. https://metanit.com/sharp/windowsforms/3.1.php

    Containers in Windows Forms

    For the organization of the management elements of the group, it is necessary to use special elements - containers. For example, Panel, FlowLayoutPanel, SplitContainer, GroupBox. The same form can be carried to containers. The choice of containers is lighter in terms of elements, and also in the form of a singing visual style.

    All containers may have the power of Controls to avenge any element of the container. If we transfer an element from the toolbar to a container, for example, a button, it will automatically be added to the collection container. Otherwise, we can also add the element of care dynamically for the additional code of the collection.

    Dynamic addition of elements
    Add a dynamic button to the form. For which dodamo I will take the form of the entanglement, in which I will create a new element of curation. You can work either for help code or visual rank.

    By dragging elements from the toolbar, we can easily add new elements to the mold. However, such a way to complete the surroundings, shards often need to dynamically create (see) the elements on the form.

    For dynamic addition of elements, we create a sample of the input form for the file code:


    {
    }
    Now add to the new code for adding a button to the form:

    Private void Form1_Load(object sender, EventArgs e)
    {


    helloButton.ForeColor = Color.DarkGray;
    helloButton.Location = NewPoint(10, 10);

    this.Controls.Add(helloButton);
    }
    On the back we create a button that is installed in power. Then, using the Controls.Add method, we add it to the collection of form elements. We didn’t break the yakby, we wouldn’t shake the button, we simply didn’t dream of splintering in any way for our form.

    For the help of the Controls.Remove() method, you can remove the element from the form before adding it:

    This.Controls.Remove(helloButton);

    If you want to use a form in this way as a container, but if you add the added elements from any other container, for example, GroupBox, you will zastosovuvatsya your own methods.

  8. https://metanit.com/sharp/windowsforms/3.2.php

    Elements GroupBox, Panel and FlowLayoutPanel

    GroupBox in a special container, which is surrounded by a cordon. Vіn maє heading, which is installed through authority Text. To spawn a GroupBox without a title, as the value of the power of the Text, an empty row is simply inserted.

    Often this element is used for grouping transitions - RadioButton elements, shards allow you to separate these groups.

    The Panel element represents a panel, like a GroupBox, that combines the elements into a group. It can be visually angry with a different shape, but it can also have a background color meaning like BackColor, which is a shape. So you can see, you can specify a color for the element to the cordon for additional power BorderStyle, as for locking the meaning of None, that is the difference between.

    Also, as the panel can have a lot of elements that go beyond the border, we can create a panel that scrolls by setting the AutoScroll power to true

    As a form, GroupBox and Panel can contain collections of elements, and we can also dynamically add elements to containers. For example, on the form there is a GroupBox element, which may be groupBox1:

    Private void Form1_Load(object sender, EventArgs e)
    {
    Button helloButton = NewButton();
    helloButton.BackColor = Color.LightGray;
    helloButton.ForeColor = Color.Red;
    helloButton.Location = new item (30, 30);
    helloButton.Text = "Hi";
    groupBox1.Controls.Add(helloButton);
    }
    To insert the layout of the element into the container, use the Point: new Point(30, 30); structure, which is passed to the constructor along the X and Y axes.

    When you need to ensure that the container of the top level is a form, and the groupBox1 element itself is in the collection of form elements. I could see yogo behind the bazhannya:

    This.Controls.Remove(groupBox1);
    FlowLayoutPanel
    The FlowLayoutPanel element collapses into the Panel class, and therefore it collapses all authority. However, adding additional functionality. So, this element allows you to change the position and layout of the child elements at the hour of the change of the time of the change of the form and at the hour of the end of the program.

    The power of the FlowDirection element allows you to set it directly, in which direction child elements. Behind the lock, the value of LeftToRight - so that the elements are rotated slowly in the direction of the left upper edge. Steps to go right-handed. This power can also take on the following meanings:

    • RightToLeft – elements are rotated from the upper right corner to the left side
    • TopDown - elements roam out of the upper left corner and go down
    • BottomUp - elements are placed in the lower left corner and go uphill

    When placing elements, an important role plays the power of WrapContents. Behind the promotions it may be True. This allows you to transfer elements that do not fit in the FlowLayoutPanel to a new row or a new page. If the value is False, then the elements are not carried over, and the container is simply scrolled around, so that the power of AutoScroll is true.
  9. https://metanit.com/sharp/windowsforms/3.3.php

    TableLayoutPanel

    The TableLayoutPanel element also re-renders the panel and can have child controls in the table view, but for the skin element it has its own room. If we want to place more than one element in the room, then another TableLayoutPanel component is added to the room, and other elements are put into it.

    In order to establish the number of rows in the columns of the tables, we can win the power of Rows and Columns obviously. Having selected one of these points at the Properties window (Power), we imagine that the next step is to set up the columns and rows:

    For the Size Type field, we can specify the size of the columns / rows. We have three possible options available:

    • Absolute: set the absolute size for rows or columns for pixels
    • Percent: the visual size is displayed in the windows. As we need to create a gum design of the form, so that the rows of tabs, as well as the elements of the keying in the middle of the table, are automatically scaled when changing the size of the form, then it is necessary to use the option itself
    • AutoSize: row height and column width are set automatically according to the size of the largest in the row or column column
    We can also combine values, for example, one column can be fixed with an absolute width, and other columns can change the width of a width.

    In this dialog box, we can also add or remove rows and columns. At the same time, the graphic designer of Visual Studio does not start adding changes to the tables - adding or adding rows and stowpts, changing their layouts, to the fact that changes on the form are not available, you need to close and then renew the designer in the graphic design.

    Also, for example, I have three rows and three rows of expansions of such similarities - 33.33%. A button has been added to the skin com_rku of the table, so that Dock=Fill can have power.

    If I change the size of the form, then the rows and columns are automatically scaled at the same time by placing buttons in them:

    What to do manually for the creation of scalable interfaces.

    We can dynamically change the values ​​of the columns and rows of the code. Moreover, all columns are represented by the ColumnStyle type, and rows by the RowStyle type:

    TableLayoutPanel1.RowStyles.SizeType = SizeType.Percent;
    tableLayoutPanel1.RowStyles.Height = 40;

    TableLayoutPanel1.ColumnStyles.SizeType = SizeType.Absolute;
    tableLayoutPanel1.ColumnStyles.Width = 50;
    To set the size in ColumnStyle and RowStyle, the power of SizeType is set, so that one sets the value of the one-name change of SizeType

    Adding an element to a TableLayoutPanel container has its own characteristics. We can add yoga to the offensive free middle, or we can show the middle of the table in an obvious order:

    Button saveButton = NewButton();
    // add the button to the upcoming mid-afternoon
    tableLayoutPanel1.Controls.Add(saveButton);
    // add a button to the commissary (2,2)
    tableLayoutPanel1.Controls.Add(saveButton, 2, 2);

    In this way, we add a button to the closet, which settles on the third row and the third row. True, since we don’t have a lot of rows and rows, the system will automatically select the required middle for adding.

  10. https://metanit.com/sharp/windowsforms/3.4.php

    Expanding the elements and their position in the container



    Position
    For the skin control, we can assign the Location power, as in assigning the coordinates of the top left corner of the element to the container. When you transfer an element from the toolbar to the form, the authority is automatically restored. Ale potim at the discretion of the authorities, we can manually correct the coordinates of the position of the element:

    We can also set the position of the element in the code:

    1
    2
    3
    4
    private void Form1_Load(object sender, EventArgs e)
    {
    button1.Location = NewPoint(50, 50);
    }
    Installation of expansions
    For additional power of Size, you can set the size of the element:

    Additions to the power of MaximumSize and MinimumSize allow you to set the minimum and maximum sizes.

    Setting powers for code:

    1
    2
    3
    4
    button1.Size = new Size ( Width = 50, Height = 25 );
    // set the powers of the okremo
    button1.Width = 100;
    button1.Height = 35;
    Power Anchor
    Added ability to position the element allows for the importance of Anchor power. The power lies between one side of the element and the other side of the container. If, when working with a container, I can pull it apart, then at the same time, it will pull out the attachments of the element.

    Behind the lock on the skin element, what do you know, its power is stronger Top, Left:

    Tse means that we will stretch the form to the left or uphill, then the element will be saved from the left and the upper border of the element to the border of the container, as the form will appear.

    We can set as many as possible values ​​for power or their combination:

  11. Right
  12. For example, as we change the meaning of the authority on the protilezhne - Bottom, Right, then we will have an invariable position between the right and lower side of the element and the form.

    At the same time, it is necessary to designate that the authority is safe in the middle of the container, and not form. So, since we have a Panel element on the form, and a button is ruffled on the Panel, then the button should be replaced by a change between the Panel, and not the form. The expansion of the form will be in the right place to pour in just a little more than it will be poured into the Panel container.

    To set the power of the code, you need to win the AnchorStyles translation:

    1
    2
    3
    button1.Anchor = AnchorStyles.Left;
    // set the value combination
    button1.Anchor = AnchorStyles.Left | AnchorStyles.Top;
    Power Dock
    The power of the Dock allows you to attach an element to the right side of a container. Behind the lock, the value is None, but it also allows you to set five values:

  • Top: the element is pushed to the top of the container
  • Bottom: the element is pressed to the bottom border of the container
  • Left: the element is pushed to the left side of the container
  • Right: the element is attached to the right side of the container
  • Fill: the element fills the entire area of ​​the container
  • https://metanit.com/sharp/windowsforms/3.5.php

    Tab Control TabControl and SplitContainer



    TabControl

    The TabControl element allows you to create a keymap element with multiple tabs. І skin tab saves a set of other control elements, like buttons, text fields and int. The skin tab is represented by the class TabPage.

    To customize the tabs of the TabControl element, using power TabPages. When the TabControl element is transferred from the toolbar to the form, two tabs are created behind the lock - tabPage1 and tabPage2. Let's change it for additional power TabPages:

    We need to edit/add that tabs view:

    The skin tab is a kind of panel, so we can add other key elements, and navigate the title, so we can navigate through the tabs. The text of the heading is set after the help Text.

    Curving with tabs at the code
    To add a new tab, we need to create and add to the tabControl1.TabPages collection behind the Add method:

    // adding a tab
    TabPage newTabPage = new TabPage();
    newTabPage.Text = "Continent";
    tabControl1.TabPages.Add(newTabPage);
    Vision is as simple as that:

    // View tabs
    // after index
    tabControl1.TabPages.RemoveAt(0);
    // by object
    tabControl1.TabPages.Remove(newTabPage);
    Otrimuyu in the collection tabControl1.TabPages will need a tab index, we can easily manipulate:

    // Change of authority
    tabControl1.TabPages.Text = "First Tab";
    SplitContainer
    The SplitContainer element allows you to create two splitter panels. By changing the position of the splitter, you can change the size of these panels.

    Victory power Orientation, you can install horizontally or vertically in the splitter on the form. In this case, the power of increasing the value of Horisontal and Vertical is obvious.

    For example, if you need to change the position of the splitter, you can set the power of IsSplitterFixed to true. In this order, the splitter will appear fixed, and we cannot change its position.

    For abbreviations, when expanding the form or sounding, the expansion of both panels of the splitcontainer is also changed. However, we can fix for one panel a fixed width (with a vertical orientation of the splitter) or height (with a horizontal orientation of the splitter). For which we need to set the power of the SplitContainer element to FixedPanel. As the meaning of the panel is being filled, it is necessary to fix it:

    To change the position of the splitter in the code, we can use the SplitterDistance power to set the position of the splitter in pixels from the left or top edge of the SplitContainer. And for the additional power of SplitterIncrement, you can set a crochet to which the splitter will move for an hour and a half for the additional arrow keys.

    To attach one of two panels, we can set the power of Panel1Collapsed or Panel2Collapsed to true

  • https://metanit.com/sharp/windowsforms/4.1.php

    Elementi keruvannya

    Elements of control over visual classes, which can take into account the input of data and can influence different subdivisions. All control elements are declining to the Control class and therefore may be low in power:

    • Anchor: Signifies how the element is pulled
    • BackColor: Sets the background color of the element
    • BackgroundImage: Displays the element's background image
    • ContextMenu: Not a context menu, as shown when the right mouse button clicks on the element. Ask for help of the ContextMenu element
    • Cursor: Specifies how the mouse cursor appears when hovering over an element
    • Dock: Set the layout of the element on the form
    • Enabled: Specifies whether the element will be available for the wiki. If the value is False, the element is blocked.
    • Font: Sets the font for the text for the element
    • ForeColor: Set the color of the font
    • Location: Shows the coordinates of the top left corner of the key element
    • Name: Im'ya element keruvannya
    • Size: Show element size
    • Width: element width
    • Height: height of the element
    • TabIndex: Specifies the order in which the element is to be traversed by pressing the Tab key
    • Tag: Allows you to save the value associated with this control element
    Button
    The most common control element is the button. Obroblyayuchi under the pressure of the button, we can work those chi іnshі dії.

    When you click on the button on the form in the Visual Studio editor, you will be dragged to the code of the Click click handler, which will be clicked when you click:

    Private void button1_Click(object sender, EventArgs e)
    {
    MessageBox.Show("Hello World");
    }
    Button decoration
    For cherishing the zvnіshnіshnіshnіshnіshnіmіbrannyam of the button, you can win the power flat style. You can take the following meaning:

    • Flat - The button may look flat.
    • Popup - The button looks big when hovering over it, in other ways it looks flat
    • Standard - Button for maximum visibility (for locking)
    • System - Type of the button to deposit in the operating system
    Image on the button
    As for the rich elements of the key, for the button you can set an image for the BackgroundImage. However, we can also change the placement of the text and the image on the buttons. Who needs to win the power of the TextImageRelation. Vono nabuvaє advancing meanings:
    • Overlay: text is overlaid on the image
    • ImageAboveText: Image above text
    • TextAboveImage: text above the image
    • ImageBeforeText: image before text
    • TextBeforeImage: text is placed before images
    For example, for the image button. For which one we select the button and the power is pressed on the Image field (do not stray from the BackgroundImage). We are presented with a dialog box for the image to be inserted:

    Select the Local Resource option and press the Import button, after which we will see a dialog box for selecting the image file.

    If you select an image, we can set the ImageAlign power, as it takes into account the position of the image on the button:

    We have 9 options available, for the help of which we can attach an image to the song side of the button. Let's leave the meaning behind the lock here - MiddleCenter, that is positioned in the center.

    Then let's move on to the power of the TextImageRelation, which is set to the new ImageBeforeText value. At the result, we take away the button, de right after the image is written on the button:

    Keys swedish access
    When working with the forms, the keyboard will be manually pressed with the keys of a quick access. When pressed on the keyboard, the combination of keys At + the same character, the same button will be called. For example, set for the current button the power of Text, which is good &Avatar. The first sign - the ampersand - signifies that letter, as if you will be lifted. At tsomu vipadku wrote bude look like an Avatar. I now podium Click it is enough for us to click on the Alt + A key combination.

    Lock buttons
    The form, on which all the control elements are located, has the power to recognize the button as a lock, that button is clicked.

    For example, the power of the AcceptButton form allows you to recognize a standard button as a way to handle hitting the Enter key.

    Similarly, the power of the CancelButton form is exercised, as it assigns a touch button. Having assigned such a button, we can click on it by pressing the Esc key.

  • https://metanit.com/sharp/windowsforms/4.2.php

    label
    To display a simple text on the form, accessible only for reading, use the Label element. To set the label text, you need to set the power of the Text element.

    Link Label
    A special type of badge is represented by LinkLabel elements, which are designated for displaying messages, similar to messages, placed on standard web pages.

    • The power of ActiveLinkColor determines the color of the force when pressed
    • The power of the LinkColor sets the color of the strength before the onslaught, for which there have not yet been transitions
    • The power of the VisitedLinkColor sets the color of the message, which is already the transition
    We can set the power of the LinkBehavior for a given element to specify the power of the LinkBehavior, as a rule, the behavior of the request. Tsya power gains some possible meanings:
    • SystemDefault: system settings are installed to enforce
    • AlwaysUnderline
    • HoverUnderline: the message only appears when the mouse is hovered over
    • NeverUnderline
    By the way, all the text on this element is respected by the authorities. However, for the additional power of the LinkArea, we can change the area of ​​the link. For example, we do not want to include the first six characters. For whom we set the Start requirement:

    In order to vikonate the transition by force of pressure on it, it is necessary to write the code additionally. This code is responsible for processing the LinkClicked sub, as the LinkLabel element can be. For example, let's have on the form the element of the force, which is called linkLabel1 and which is to avenge the force:

    Public partial class Form1: Form
    {
    Public Form1()
    {
    InitializeComponent();
    // set the pod_obrobnik
    linkLabel1.LinkClicked += linkLabel1_LinkClicked;
    }

    Private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
    System.Diagnostics.Process.Start("http://metanit.com");
    }
    }
    The System.Diagnostics.Process.Start() method is requested by the web browser, which is installed in the system by the browser behind a promotion.

  • https://metanit.com/sharp/windowsforms/4.3.php

    TextBox

    For the introduction and editing of the text, a text field is assigned - the TextBox element. So just like the Label element, the text of the TextBox element can be inserted or taken for additional authority Text.

    By default, when moving an element from the toolbar, a text field is created. In order to display great communication in the text field, it is necessary to highlight the power of Multiline and ScrollBars. If Multiline authority is set to true, all superfluous characters that appear outside the fields will be transferred to the new row.

    In addition, you can make the text field scroll by setting ScrollBars to one of the following values:

    • None: no scrolling (no scrolling)
    • Horizontal: creates a horizontal scroll when the row is full, which shifts the width of the text field
    • Vertical: creates vertical scrolling so the rows don't nest in the text field
    • Both: scroll vertically and horizontally

    Autocomplete text field
    The TextBox element may be able to create an autocomplete field. For whom we need to tie power AutoCompleteCustomSource of the TextBox element to a specific collection, for which the given fields are taken.

    Then, add a text field to the form and write it in the code for subdividing the next row:

    Public partial class Form1: Form
    {
    Public Form1()
    {
    InitializeComponent();
    AutoCompleteStringCollection source = new AutoCompleteStringCollection()
    {
    "Kovaliv",
    "Іvaniv",
    "Petriv",
    "Kustiv"
    };
    textBox1.AutoCompleteCustomSource = source;
    textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
    textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
    }
    }

    Autocompletion mode, power representations in AutoCompleteMode, may have a few possible values:

    • None: auto-completion allowed
    • Suggest: suggest options for introduction, but do not add
    • Append: append the value to the row in the list, but do not pass the selection option
    • SuggestAppend: one hour and suggest options for auto-completion, that add the value you enter
    Translation for words
    So that the text in the TextBox element wraps behind words, you need to set the authority word wrap equal true. So that one word does not fit in a row, but is transferred to the offensive. Tsya power bude pratsyuvati less for variegated text fields.

    Password entry
    Also, this element has the power to allow you to enter a new field for entering a password. So, for which you need to hack PasswordChar and UseSystemPasswordChar.

    The power of the PasswordChar cannot be locked, so if we set it to any character, that character will be displayed when any character is entered in the text field.

    The power of UseSystemPasswordChar can be controlled. If we set this value to true, instead of the entered characters in the text field, the sign of the password will be displayed, accepted in the system, for example, a period.

    Podiya TextChanged
    The last sub of the TextBox element should be set to the TextChanged sub, which is used when changing the text of the element. For example, let's change the label on the shape of the crim text field so that when you change the text in the text field, you also change the text on the label:

    Public partial class Form1: Form
    {
    Public Form1()
    {
    InitializeComponent();

    TextBox1.TextChanged += textBox1_TextChanged;
    }

    Private void textBox1_TextChanged(object sender, EventArgs e)
    {
    label1.Text = textBox1.Text;
    }
    }

  • https://metanit.com/sharp/windowsforms/4.4.php

    The MaskedTextBox element

    The MaskedTextBox element truly represents a normal text box. However, this element allows you to control the introduction of koristuvach and recheck it automatically for the presence of pardons.

    To control the characters that are entered in the fields, you need to set a mask. To create a mask, you can twist the following symbols:

    • 0: Allow extra numbers to be entered
    • 9: Allows you to enter numbers and probіl
    • #: Allows you to enter numbers, probіl and signs "+" and "-"
    • L: Allows you to enter extra literal characters
    • ?: Allows you to enter optional non-language literal characters
    • A: Allows you to enter letters and digits
    • .: Set the position of the splitter of the whole and the shot part.
    • ,: Victory for sub-rows at the whole part of the number.
    • :: Vikoristovuetsya in hourly intervals - splitting years, hvilini that second
    • /: Victory for sub-dates
    • $: Wink as a currency symbol
    To set the mask, you need to set the power of the Mask element. Knowing the power of the Porperties, we will press on a new one and imagine it for setting one of the standard mask templates. So, we can select the Phone number, which is the same as the input in the text box, instead of the phone number:

    Now, at startup, we can enter more than a number in the text field, leaving the phone number.

    Now let's put on our mask. For example, let's create a mask for entering the initials of the name according to the father's name and the name of the old man in the text field. For whom do you think the power of Mask means L.L.L ?????????. Then the entry in the text field will look like this:

    This element also represents a number of authorities, which can be used to control the introduction. So, the power of BeepOnError when set to true gives beep p_d hour of entering an incorrect character.

    The power of HidePromptOnLeave when set to true when the text field is entered has the focus set to PromptChar

    The power of PromptChar indicates the character that appears in the input character space. Behind the castle there is a sign of reassurance.

    The AsciiOnly power, set to true, allows you to enter only asci characters, such as characters in the range A-Z and a-z.

  • https://metanit.com/sharp/windowsforms/4.5.php

    Radiobutton and CheckBox elements

    checkbox
    The CheckBox element is either a flag of assignments for setting one of two values: checked or not set. To set the ensign, you need to set the authority Checked to true.

    Checked authority limit for the CheckBox element - CheckState authority, which allows you to set one of the three states for the ensign - Checked (values), Indeterminate (the ensign of not assigned - noted, or be in an inactive state) and Unchecked (not noted)

    Also, set the authority of AutoCheck - if it can be false, then we cannot change the ensign. Behind the promotion it may be true.

    At the time of the change, I will become the proportsia of the wines and generate the CheckedChanged subdomain. Obroblyayu tsyu podіyu, we can take away the changes ensign and robiti sevni dії:

    Private void checkBox_CheckedChanged(object sender, EventArgs e)
    {
    CheckBox checkBox = (CheckBox) sender; // Hover the guide to an element of the CheckBox type
    if (checkBox.Checked == true)
    {
    MessageBox.Show("Ensign" + checkBox.Text + "now set");
    }
    else
    {
    MessageBox.Show("Ensign" + checkBox.Text + "no values ​​now");
    }
    }
    radiobutton
    On the CheckBox element, there is a similar RadioButton element or a jumper. The switches are arranged in groups, and the inclusion of one switch means the inclusion of a decision.

    To install a stun at the jumper, you need to take power Checked true.

    To create a group of jumpers, from which you can choose, you need to place a bunch of jumpers in a container, for example, the GroupBox or Panel elements. Transmitters. what is in different containers will be added to different groups:

    In a similar rank, we can change the permutation in the group, shaping the CheckedChanged subdivision. By linking the leather jumper of the group with one sample of this podії, we can take that jumper, which is a call at the given moment:

    Private void radioButton_CheckedChanged(object sender, EventArgs e)
    {
    // Hover the guide to the element of type RadioButton
    RadioButton radioButton = (RadioButton) sender;
    if (radioButton.Checked)
    {
    MessageBox.Show("You selected" + radioButton.Text);
    }
    }

  • https://metanit.com/sharp/windowsforms/4.6.php

    list box

    The ListBox element is simply a list. The key power of this element is the power of Items, so that you can select all the elements in the list.

    Elements can be added to the list as soon as the opening hour, so i programmatically. In Visual Studio, at the Properties (Power) of the ListBox element, we can know the power of the Items. After a subway clatter on power, we see it in the window to add the elements to the list:

    For an empty field, one element of the list is entered - one per skin row. After that, all the elements added by us will be in the list, and we can manage them:

    Programmatically picking items from a ListBox
    Adding elements
    Otzhe, all elements of the list are included in the power of Items, as a collection. To add a new item to the collection, i.e. to the list, you need to select the Add method, for example: listBox1.Items.Add("New item"); With the help of this method, the skin element, which is added, is added to the end of the list.

    You can add a sprinkling of elements, for example, an array. For which the AddRange method is used:

    String countries = ("Brazil", "Argentina", "Chile", "Uruguay", "Colombia");
    listBox1.Items.AddRange(countries);
    Inserting elements
    On the view of a simple addition, the insert is placed after the first index of the list after the help method Insert:

    ListBox1.Items.Insert(1, "Paraguay");
    In this view, we insert an element at a different position in the list, so that the given position starts from scratch.

    View of elements
    To remove an element behind the text, the Remove method is used:

    ListBox1.Items.Remove("Numbers");
    To remove the element behind the index in the list, the RemoveAt method is used:

    ListBox1.Items.RemoveAt(1);
    In addition, you can clear the entire list at once by calling the Clear method:

    ListBox1.Items.Clear();
    Access to elements of a list
    Vykoristovuyuchi element index, you can element in the list. For example, take the first element of the list:

    String firstElement=listBox1.Items;
    The Count method allows you to assign the number of elements in the list:

    Int number = listBox1.Items.Count();
    Seeing items in the list
    When the elements of the list are seen, we can manage them both through the index, and through the seen element itself. You can take a look at the elements with the help of such powers of the ListBox element:

    • SelectedIndex: rotate or insert the number of the seen list. How to see the elements of the day, the same power may have a value -1
    • SelectedIndices: rotate or set the collection of visible elements to the selected set of indexes
    • SelectedItem: rotate or insert the text of the seen item
    • SelectedItems: rotate or insert visible items in the selected collection
    As a reminder, the list supports the sighting of one element. To add the ability to see a few elements, it is necessary to set the SelectionMode value to MultiSimple in its SelectionMode power.

    To see an element programmatically, call the SetSelected (int index, bool value) method, where index is the number of the seen element. If another parameter - value can be true, then the element behind the specified index is visible, if it is false, then the visualization is immediately received:

    ListBox1.SetSelected(2, true); // will see the third element
    To capture the view of the selected elements, the ClearSelected method is used.

    Podiya SelectedIndexChanged
    The list box element must have a list box before the SelectedIndexChanged sub-item, which is the result of changing the seen item:

    Public partial class Form1: Form
    {
    Public Form1()
    {
    InitializeComponent();

    String countries = ("Brazil", "Argentina", "Chile", "Uruguay", "Colombia");
    listBox1.Items.AddRange(countries);
    listBox1.SelectedIndexChanged += listBox1_SelectedIndexChanged;
    }

    Void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
    string selectedCountry = listBox1.SelectedItem.ToString();
    MessageBox.Show(selectedCountry);
    }
    }
    If you choose to select an element, the list should be revisited with the visible element.

    comboBox1.Items.AddRange(new string ("Uruguay", "Ecuador"));
    // Add one element per single position
    comboBox1.Items.Insert(1, "Bolivia");
    When adding additional Add/AddRange methods, all new elements are placed in the list. However, if we set the ComboBox to power Sorted equal to true, then sorting will be automatically performed when added.

    View of elements:

    // We render one element
    comboBox1.Items.Remove("Argentina");
    // View element after index
    comboBox1.Items.RemoveAt(1);
    // View all elements
    comboBox1.Items.Clear();
    We can take the element behind the index and work with it differently. For example, change yoga:

    ComboBox1.Items = "Paraguay";
    Customizing the design of the ComboBox
    With the help of low power, you can tweak the style of the component. So, the power of DropDownWidth sets the width of the dropdown list. For the added power of DropDownHeight, you can set the height of the list.

    Another power of MaxDropDownItems allows you to set the number of visible items in the list - from 1 to 100. For locking, the number is 8.

    More power DropDownStyle sets the style of the ComboBox. You can take three possible meanings:

    • Dropdown: win for the lockdown. We can enter a list of options that will appear when you enter a value in the text field, or by clicking on the button with the arrow in the right part of the element, and we will see a list in which you can select a possible option
    • DropdownList: to drop the dropdown list, you need to click on the button with the arrow on the right side of the element
    • Simple: ComboBox is a simple text box where we can scroll keyboard keys up/down to move between items.

    Podiya SelectedIndexChanged
    The most important sub for the ComboBox is also the SelectedIndexChanged sub, which allows you to select an item from the list:

    Public partial class Form1: Form
    {
    Public Form1()
    {
    InitializeComponent();

    ComboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
    }

    Void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
    string selectedState = comboBox1.SelectedItem.ToString();
    MessageBox.Show(selectedState);
    }
    }
    Here, too, the power of SelectedItem is given to the selected element.

  • Now the hour has come to create our first great addition.
    Important those that are seen in this part:
    The addendum, which is being expanded, will be a small form, which I repeat the idea of ​​a program invented a long time ago: on the form there will be food "". When trying to point the browser at the button " So cool! you will always tick at us. Push button " Hi you will not be surrounded by anything.


    Creating this program, we can look at the main principles of the creation of all supplements C#, and navіt methods of implementation with the help of them, whether they are endemic goals: in times - tse comedly ticking all the time.

    Create a new project, install the program as a template Windows Forms, as shown in little 1:
    1. Creation of a new project.
    Name the project RandWindow and press the button OK.

    Working vikno MS Visual Studio to avenge the onset of additional lapses (Fig. 2).

    2. Additional windows.
    On a tiny number of numbers it is marked:

    1. Vikno Toolbox(Panel of control elements) - control elements you can place on the form that is being created.

    2. Vikno solution explorer(Oglyadach decision) - here you can make such knots: Properties- adjusting the project, Links(Possilannya) - connection to the library project, as well as the creation and connection to the project of files of external codes (with extensions .cs) and connected to the draft form (for example, Form1).

    3. Vikno class view(Vіkno class) – here you can see all creations of the program class.

    4. Vikno Properties(Powerfulness) - Selecting whether there is an element of carving or creating a form, you can work out all the parameters of this object, as well as change the value set for the lock.

    The creation of the windows programs is carried out until the creation of all the necessary dialogue windows, as well as the placement of the necessary elements on them. Nadali mi nalashtovuemo podia, making them coristuvachem, that nalashtovuemo technical aspects of robotic programs. In our mind, we have placed all the necessary control elements on the main form, after which we add a control for moving the mouse and a control for pushing buttons.

    Adding new elements to the form

    Then, after that, you entered the name of the project, inserted the required template and pressed the button OK, MS Visual Studio automatically create the frame of the window program, after which we can add new window elements.

    For which it is necessary to drag the necessary window element from the tool window ( toolbox).

    Our viknu needs 2 element of the input field, in which it displays the coordinates of the mouse's input, which will make it easier for us to understand the work of the program.

    At the center of the window will be written, which we create for the help of the element label.
    The bottom will be stitched 2 buttons.

    Trochs stretch the workpiece of the vikna. If you press on the new one with the right button, you will see context menu. Have a new one to press on the point of authority, if you can change the parameters of the window, you can change it. For a little 3 images, the most (as a rule) necessary authority:
    Figure 3. Different power levels of a window (form) in C# .NET.
    Troch to stretch the workpiece of the window and add all the necessary elements. For little 4 you can slap them at the window toolbox:

    Baby 4. Drag and drop the Toolbox Width Elements onto the folded shape.

    Go to the authorities of the row Label1 change the text to " Will you work to build the light of the best?". Also change the font type, for which you know the authority Font(Fig. 5).
    5. Authority Font of the Label element.
    After what set the font type Tahoma, font width Bold and rozmir equal 16 (Fig. 6).

    Figure 6. Adjusting the font.
    Allowed to change the text on the buttons, vicorist power Text.

    Otriman's workpiece vykna program looks like this (Fig. 7).

    Figure 7. The shape looks like this.

    Technical part of robotic programs

    1. On the back of my hand dodamo a sample of the movement of the mouse and the realizable view of the coordinates xі y two creations of the input field.
    2. Let's create the functions of clattering on the skin keys of the mouse (especially the straps of the coristuvach, you can still use the button " So cool!»).
    3. Give us a code that implements the way the window moves to the right way, so that the cursor gets close to the button « So cool!».

    Significant movement of the mouse by the form

    Click indiscriminately on the part of the form of the program that is being created ( NOT one of the elements).

    Now go to the power of the form for the help of clicking the right button of the mouse -> context menu authority.

    Now it is necessary to go to the list of possible podias, yakі can win victoriously. For whom click on the button " event"(Podії), as shown in the little 8:
    8. Move to the list of possible entries.
    If the koristuvach transfers the mouse to the window, operating system Sending help to the program with the current coordinates of the indicator. Stink and need us.

    To recognize the obrobnik tsієї podії, know the row MouseMove(small 9), after which the clatter in the field is right-handed, it will automatically give a copy of the mouse’s hand and the function will be given Form1_MouseMove at the code of our program.
    Figure 9. After a right-handed click, the right-handed MouseMove will appear in the row, and the transition to the code of the function-computer will be automatically created.
    Add 2 rows to this function so that the code looks like this.

    /*http://website, Anvi*/ private void Form1_MouseMove(object sender, MouseEventArgs e) ( // move the X coordinate to the row and write it to the input fields textBox1.Text = e.X.ToString(); // move the Y coordinate to the row it writes to the input fields textBox2.Text = e.Y.ToString();
    This function, which converts the sub-move of the mouse indicator above the form, eliminates 2 Parameter: Object wdRunner and Instance to class MouseEventsArgs, to avenge information about the coordinates of the target’s destination and other current authorities.

    textBox1і textBox2 ce instance of the class text box, which is implemented by our input field elements.

    Member of these instances Text Allows you to insert text in these fields.

    In this rank, now you have to compile the program ( F5), when moving the indicator of the mouse behind the form of the window, we still have the coordinates of the indicator (in the middle of the form), which change without interruption.

    Now let's turn to the preparation of our form. For whom click on the special bookmark (Form1.cs [Constructor]), as shown in little 10:
    10. Jump to the C# form constructor.
    Create a subway click on the first button: visual studio automatically add the code for the processing of the button when pressed.

    Add next rows to the code:

    /*http://website, Anvi*/ private void button1_Click(object sender, EventArgs e) ( // Show a message with the text "You're in" MessageBox.Show("You're in!!"); // Terminate the Application. Exit(); )
    Now I'll turn back to the constructor and give a friend a button also for the help of a floating click on it.

    /*http://website, Anvi*/ private void button2_Click(object sender, EventArgs e) ( // Enter an alert, with the text "We didn't doubt your buy" // another parameter is the caption of the alert message "Uvaga" // MessageBoxButtons.OK - type of button on the notification form // MessageBoxIcon.Information - type of notification - matima the "information" icon and an audible sound MessageBox.Show("We didn't hesitate about your important request","Uvaga", MessageBoxButtons.OK, MessageBoxIcon. Information);
    Like a bachite, mi trochs have folded the code for a weekly vacancy-information, in order to demonstrate how it works, more report. Mustache parameters that are passed to the function show commented out at the output code.

    Now we have no more realizing the movement of the window at the moment when the mouse approaches the button. So cool».

    For which mi dodamo the code for the function:

    private voidForm1_MouseMove(object sender, MouseEventArgs)

    The principle is even simpler: by taking the coordinates of the mouse's hand, we will change it, so as not to enter the stink at the square, which christens our button with a small margin. If so, then we will generate 2 decimal numbers, which will be victories for moving the window.

    We could just notify you about pointing the mouse indicator at the button, but it will come with a commemorative blur, at the link with which the coristuvach without special pressure is pressed on the button so that we simply put the cursor in the zone near the button.

    So we need to voice deshcho " workers"Smіnnih, yakі we'll give victorious.

    Generation of upright numbers

    class Random in C#є generator of pseudovipad numbers - tobto. This class is distinguished for the type of sequence of numbers, which is consistent with the statistical criteria of vipadkovnosti.

    Random rnd = New Random();

    Here we voiced an instance of the class Random (rnd), for the help of such a vipadkovі number. Nadalі we will beat the code, mind rnd.Next(generation_range) or rnd.Next(from to -1 ) to generate vipadic number.

    So we will voice a little more of the change, some of them will be immediately initiated.

    Windows.Forms.SystemInformation.PrimaryMonitorSize.Width; int _h = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Height;
    tmp_location goloshuetsya at that, schob at the future timchasovo save the camp of vikna.

    So we should think about those who, in the case of a vertical shift, our window can go far beyond the borders of the screen.

    shob assign the screen to C# .NET , we will vikoristovuvaty:

    /*http://site, Anvi*/ System.Windows.Forms.SystemInformation.PrimaryMonitorSize
    _hі _w take care of your own screen koristuvach, as it is charged for initialization.
    Now the code for this function looks like this:

    /*http://esate.ru, Anvi*/ private void Form1_MouseMove(object sender, MouseEventArgs e) ( // transfer the X coordinate to the row and write it to the input fields textBox1.Text = e.X.ToString(); // transfer the Y coordinate in a row and write to the input fields textBox2.Text = e.Y.ToString(); // so the coordinate along the X axis and along the Y axis lie in the square if, which is labeled next to the "so, wonderfully" button (e.X > 80 && e.X 100 && e.Y (_w - this.Width/2) ||tmp_location.Y(_h - this.Height/2)) , on the new generated this.Location = tmp_location;))
    Axis, vlasne, and that's it. After completing the program, you can try to click on the button "So, it's amazing." Tse will be more important.

    Last updated: 31.10.2015

    For the creation of graphical interfaces for the additional .NET platform, various technologies are deployed - Window Forms, WPF, add-ons for the Windows Store (for Windows 8/8.1/10). However, the most simple and handy dossier platform is Window Forms or Forms. Danish help put as a metadata of understanding the principles of the creation of graphical interfaces for the additional WinForms technology and the work of the main elements of management.

    Created by graphic software

    To create a graphic project, we need the Visual Studio development environment. Since the version of Visual Studio 2013 is the most expanded so far, then for whom I help, I'll beat the cost-free version of this medium Visual Studio Community 2013 Yaku can be found on the side https://www.visualstudio.com/en-us/products/visual-studio-community-vs.aspx.

    After installing the middleware and all its components, launch Visual Studio and create a graphics program project. For which, in the menu, select the File item (File), and in the submenu, select New -> Project (Create -> Project). The last thing we see before us is the dialogue window of the creation of a new project:

    In the left column select Windows Desktop, and in the central part of the middle project types - type Windows Form Application and for a lady, I’m like I’m in the field below. For example, we call yoga helloapp. The next thing is pressed OK.

    After Visual Studio opens the project from the files created behind the lock:

    Most of the scope of Visual Studio is occupied by a graphic designer, who can take the shape of a future program. For the time being, it's empty and there is no more than the heading Form1. On the right you can find the solution/project files - Solution Explorer. There you can find all the files related to our addendum, including the files of the form Form1.cs.

    At the bottom, the right-hander is known as the window of authority - Properties. Since at this moment I have chosen the form as an element of control, then in which field the authorities appear, tied with the form.

    Now we know the power of the form Text and change its meaning to be-yak else:

    In this way, we changed the title of the form. Now transferable to the field is a key element, for example, a button. For whom do we know the left part of Visual Studio tab Toolbox. Click on this tab, and we will see a panel with elements, we can transfer the stars to the form for any other element:

    We know the middle elements of the i button, having loaded її in the mouse’s kazіvnik, we transfer it to the form:

    Tse is a visual part. Now let's get down to programming. Let me add the simplest code of my C#, a kind of activating and pushing buttons. For whomever I am guilty, go to the code file, which is the connection from this form. Since we do not have a code file to view, we can click on the form with the right mouse button and in the View Code menu (View the code file):

    However, we will speed it up in a different way, so as not to write too much code. Hover the mouse pointer at the button and click on the lower clicks. We automatically consume the code file Form1.cs, which looks like this:

    Using System; vicorist System.Collections.Generic; using System.ComponentModel; using System.Data; vicorist System.Drawing; using System.Linq; using System.Text; vicorist System.Threading.Tasks; using System.Windows.Forms; namespace HelloApp ( public partial class Form1: Form ( public Form1() ( InitializeComponent(); ) private void button1_Click(object sender, EventArgs e) ( ) )

    Dodamo displaying a notification after pressing the button, changing the code in the following order:

    Using System; vicorist System.Collections.Generic; using System.ComponentModel; using System.Data; vicorist System.Drawing; using System.Linq; using System.Text; vicorist System.Threading.Tasks; using System.Windows.Forms; namespace HelloApp ( public partial class Form1: Form ( public Form1() ( InitializeComponent(); ) private void button1_Click(object sender, EventArgs e) ( MessageBox.Show("Hello"); ) ) )

    Launching the program

    To run the program in boot mode, press the F5 key or the green arrow on the Visual Studio panel. The next time our form starts up with the button itself. And if we press the button on the form, then we will be shown a reminder about vaping.

    After launching the program, the studio compiles yoga from the file from the extension exe. You can find the file by going to the project folder and going to the bin/Debug or bin/Release directory

    Having looked briefly at the creation of a graphic supplement to the project, we can move on to an overview of the main components and, of course, forms.

    © 2022 androidas.ru - All about Android