Windows Forms program download how to add. Programming in .NET Framework. Tests for LoginPresenter
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
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
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
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
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
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 tickedPublic 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:- We write the interface of the Appearance, the interface of the Model (as required).
- It is realizable by the Representative, prima facie virishivshi, so that we will in the new transfer this data as a model.
- [Optional] We write a test for the Representative, we will change our minds, everything is fine.
- [Optional] Implementable Model and test for it.
- We give the form and implement the interface of the Appearance.
You can pick up a demo project from
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:
- Vikno Toolbox(Panel of control elements) - control elements you can place on the form that is being created.
- 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).
- Vikno class view(Vіkno class) – here you can see all creations of the program class.
- 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
- 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.
- 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!»).
- 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.