- Пошаговое руководство. Отладка формы Windows Form Walkthrough: Debugging a Windows Form
- Чтобы подготовиться к выполнению данного пошагового руководства To prepare for this walkthrough
- Создание новой формы Windows Forms. Create a New Windows Form
- Чтобы создать форму Windows Forms для данного примера To create the Windows form for this walkthrough
- Отладка формы Debug Your Form
- Чтобы выполнить отладку формы Windows Forms, созданной для данного примера To debug the Windows Form created for this walkthrough
- Присоединение к приложению Windows Form для отладки Attach to Your Windows Form Application for Debugging
- Присоединение к приложению Windows Form для отладки To attach to the Windows Form Application for debugging
- Walkthrough: Debug Custom Windows Forms Controls at Design Time
- Create the project
- Create the control library project
- Checkpoint
- Add a property to your custom control
- Add your custom control to the host form
- Set up the project for design-time debugging
- Debug your custom control at design time
- Next steps
Пошаговое руководство. Отладка формы Windows Form Walkthrough: Debugging a Windows Form
Форма Windows Forms — один из наиболее распространенных вариантов управляемых приложений. A Windows Form is one of the most common managed applications. На основе формы Windows Forms создается стандартное приложение Windows. A Windows Form creates a standard Windows application. Можно реализовать данный примере на Visual Basic, C# или C++. You can complete this walkthrough using Visual Basic, C#, or C++.
Для начала необходимо закрыть и открыть решения. First, you must close any open solutions.
Чтобы подготовиться к выполнению данного пошагового руководства To prepare for this walkthrough
- Если какое–либо решение уже открыто, закройте его. If you already have an open solution open, close it. (В меню Файл выберите команду Закрыть решение.) (On the File menu, select Close Solution.)
Создание новой формы Windows Forms. Create a New Windows Form
Далее нам предстоит создать новую форму Windows Forms. Next, you will create a new Windows Form.
Чтобы создать форму Windows Forms для данного примера To create the Windows form for this walkthrough
В меню Файл последовательно выберите пункты Создать и Проект. On the File menu, choose New and click Project.
Откроется диалоговое окно Новый проект . The New Project dialog box appears.
В области «Типы проектов» разверните узел Visual Basic, Visual C# или Visual C++ , затем In the Project Types pane, open the Visual Basic, Visual C#, or Visual C++ node, then
для Visual Basic или Visual C# выберите Классическое приложение Windows > Приложение Windows Form. For Visual Basic or Visual C#, select Windows Desktop > Windows Form App.
Для Visual C++ выберите Классическое приложение Windows. For Visual C++, select Windows Desktop Application.
В поле Имя задайте уникальное имя проекта (например, Walkthrough_SimpleDebug). In the Name box, give the project a unique name (for example, Walkthrough_SimpleDebug).
Нажмите кнопку ОК. Click OK.
Visual Studio создаст новый проект и откроет новую форму в конструкторе Windows Forms. Visual Studio creates a new project and displays a new form in the Windows Forms designer. Дополнительные сведения см. в разделе Конструктор Windows Forms. For more information, see Windows Forms Designer.
В меню Вид выберите пункт Панель элементов. On the View menu, select Toolbox.
Откроется Панель элементов. The Toolbox opens. См. дополнительные сведения о панели элементов. For more information, see Toolbox.
В панели элементов щелкните элемент управления Кнопка и перетащите его на поверхность разработки формы. In the Toolbox, click on the Button control and drag the control to the Form design surface. Опустите кнопку на форму. Drop the button on the form.
В панели элементов щелкните элемент управления Текстовое поле и перетащите его на поверхность разработки формы. In the Toolbox, click on the TextBox control and drag the control to the Form design surface. Бросьте Текстовое поле в форму. Drop the TextBox on the form.
На поверхности разработки формы дважды щелкните кнопку. On the form design surface, double-click the button.
Появится страница кода. This takes you to the code page. Курсор должен находиться в тексте button1_Click The cursor should be in button1_Click .
В функции button1_Click добавьте следующий код: In the function button1_Click ., add the following code:
В меню Сборка выберите команду Собрать решение. On the Build menu, select Build Solution.
Проект должен быть построен без ошибок. The project should build with no errors.
Отладка формы Debug Your Form
Теперь все готово для того, чтобы начать отладку. Now, you are ready to begin debugging.
Чтобы выполнить отладку формы Windows Forms, созданной для данного примера To debug the Windows Form created for this walkthrough
В окне исходного кода щелкните левое поле на той же строке, в которую добавляется текст: In the source window, click the left margin on the same line as the text you added:
Появится красная точка, и текст строки будет выделен красным цветом. A red dot appears and the text on the line is highlighted in red. Красная точка представляет точку останова. The red dot represents a breakpoint. Дополнительные сведения см. в разделе Точки останова. For more information, see Breakpoints. Если приложение запускается из отладчика, выполнение этого приложения будет приостановлено отладчиком на строке с помеченным кодом. When you run the application under the debugger, the debugger will break execution at that location when the code is hit. После этого можно просмотреть состояние приложения и произвести его отладку. You can then view the state of your application and debug it.
Можно также щелкнуть правкой кнопкой мыши любую строку кода, выбрать пункт Точка останова, затем щелкнуть Вставить точку останова, чтобы добавить точку останова в эту строку. You can also right-click any line of code, point to Breakpoint, and then click Insert Breakpoint to add a breakpoint on that line.
В меню Отладка выберите команду Пуск. ON the Debug menu, choose Start.
Запустится форма Windows Forms. The Windows Form starts running.
В форме Windows Forms щелкните добавленную кнопку. On the Windows Form, click the button you added.
После этого в Visual Studio приложение остановится на той строке, где была задана точка останова на странице кода. In Visual Studio, this takes you to the line where you set your breakpoint on the code page. Эта строка будет выделена желтым цветом. This line should be highlighted in yellow. Теперь можно просматривать переменные в приложении и управлять его выполнением. You can now view the variables in your application and control its execution. В этот момент приложение остановит свое выполнение и будет ожидать действий со стороны пользователя. Your application has now stopped executing, waiting for an action from you.
В меню Отладка выберите пункт Окна, затем Контрольные значения и потом Контрольные значения 1. On the Debug menu, choose Windows, then Watch, and click Watch1.
В окне Контрольные значения 1 щелкните пустую строку. In the Watch1 window, click on a blank row. В столбце Имя введите textBox1.Text (если используется Visual Basic или Visual C#) или textBox1->Text (если используется C++), затем нажмите клавишу ВВОД. In the Name column, type textBox1.Text (if you are using Visual Basic or Visual C#) or textBox1->Text (if you are using C++), then press ENTER.
Окно Контрольные значения 1 отобразит значение этой переменной в двойных кавычках, как показано ниже: The Watch1 window shows the value of this variable in quotation marks as:
В меню Отладка выберите команду Выполнять по шагам. On the Debug menu, choose Step Into.
Значение textBox1.Text в окне Контрольные значения 1 изменится на следующее: The value of textBox1.Text changes in the Watch1 window to:
Button was clicked!
В меню Отладка выберите команду Продолжить для возобновления отладки программы. On the Debug menu, choose Continue to resume debugging your program.
В форме Windows Forms снова нажмите кнопку. On the Windows Form, click the button again.
Visual Studio снова приостановит выполнение программы. Visual Studio breaks execution again.
Щелкните красную точка, представляющую точка останова. Click on the red dot that represents the breakpoint.
Это действие удалит точка останова из кода программы. This removes the breakpoint from your code.
В меню Отладка выберите Остановить отладку. On the Debug menu, choose Stop Debugging.
Присоединение к приложению Windows Form для отладки Attach to Your Windows Form Application for Debugging
В Visual Studio Visual Studio можно присоединить отладчик к выполняющемуся процессу. In Visual Studio Visual Studio , you can attach the debugger to a running process. Если используется экспресс-выпуск, эта функция не поддерживается. If you are using an Express Edition, this feature is not supported.
Присоединение к приложению Windows Form для отладки To attach to the Windows Form Application for debugging
В созданном ранее проекте щелкните левое поле, чтобы еще раз установить точка останова на добавленной строке: In the project you created above, click in the left margin to once again set a breakpoint at the line you added:
В меню Отладка выберите команду Запуск без отладки. On the Debug menu, select Start Without Debugging.
Форма Windows Forms запустится из Windows, как и при двойном щелчке исполняемого файла. The Windows Form starts running under Windows, just as if you had double-clicked its executable. Отладчик не будет присоединен. The debugger is not attached.
В меню Отладка выберите команду Присоединиться к процессу. On the Debug menu, select Attach to Process. (Эта команда также доступна из меню Средства.) (This command is also available on the Tools menu.)
Откроется диалоговое окно Присоединение к процессу . The Attach to Process dialog box appears.
В области Доступные процессы найдите в столбце Процесс имя процесса (Walkthrough_SimpleDebug.exe) и щелкните его. In the Available Processes pane, find the process name (Walkthrough_SimpleDebug.exe) in the Process column and click it.
Нажмите кнопку Присоединиться. Click the Attach button.
В форме Windows Forms нажмите единственную кнопку. In your Windows Form, click the one and only button.
Отладчик прервет выполнение формы Windows Forms на точке останова. The debugger breaks execution of the Windows Form at the breakpoint.
Walkthrough: Debug Custom Windows Forms Controls at Design Time
When you create a custom control, you will often find it necessary to debug its design-time behavior. This is especially true if you are authoring a custom designer for your custom control. For details, see Walkthrough: Creating a Windows Forms Control That Takes Advantage of Visual Studio Design-Time Features.
You can debug your custom controls using Visual Studio, just as you would debug any other .NET Framework classes. The difference is that you will debug a separate instance of Visual Studio that is running your custom control’s code.
Create the project
The first step is to create the application project. You will use this project to build the application that hosts the custom control.
In Visual Studio, create a Windows Application project, and name it DebuggingExample.
Create the control library project
Add a Windows Control Library project to the solution.
Add a new UserControl item to the DebugControlLibrary project. Name it DebugControl.
In Solution Explorer, delete the project’s default control by deleting the code file with a base name of UserControl1.
Build the solution.
Checkpoint
At this point, you will be able to see your custom control in the Toolbox.
To check your progress, find the new tab called DebugControlLibrary Components and click to select it. When it opens, you will see your control listed as DebugControl with the default icon beside it.
Add a property to your custom control
To demonstrate that your custom control’s code is running at design-time, you will add a property and set a breakpoint in the code that implements the property.
Open DebugControl in the Code Editor. Add the following code to the class definition:
Build the solution.
Add your custom control to the host form
To debug the design-time behavior of your custom control, you will place an instance of the custom control class on a host form.
In the «DebuggingExample» project, open Form1 in the Windows Forms Designer.
In the Toolbox, open the DebugControlLibrary Components tab and drag a DebugControl instance onto the form.
Find the DemoString custom property in the Properties window. Note that you can change its value as you would any other property. Also note that when the DemoString property is selected, the property’s description string appears at the bottom of the Properties window.
Set up the project for design-time debugging
To debug your custom control’s design-time behavior, you will debug a separate instance of Visual Studio that is running your custom control’s code.
Right-click on the DebugControlLibrary project in the Solution Explorer and select Properties.
In the DebugControlLibrary property sheet, select the Debug tab.
In the Start Action section, select Start external program. You will be debugging a separate instance of Visual Studio, so click the ellipsis ( ) button to browse for the Visual Studio IDE. The name of the executable file is devenv.exe, and if you installed to the default location, its path is %ProgramFiles(x86)%\Microsoft Visual Studio\2019\ \Common7\IDE.
Select OK to close the dialog box.
Right-click the DebugControlLibrary project and select Set as StartUp Project to enable this debugging configuration.
Debug your custom control at design time
Now you are ready to debug your custom control as it runs in design mode. When you start the debugging session, a new instance of Visual Studio will be created, and you will use it to load the «DebuggingExample» solution. When you open Form1 in the Forms Designer, an instance of your custom control will be created and will start running.
Open the DebugControl source file in the Code Editor and place a breakpoint on the Set accessor of the DemoString property.
Press F5 to start the debugging session. A new instance of Visual Studio is created. You can distinguish between the instances in two ways:
The debugging instance has the word Running in its title bar
The debugging instance has the Start button on its Debug toolbar disabled
Your breakpoint is set in the debugging instance.
In the new instance of Visual Studio, open the «DebuggingExample» solution. You can easily find the solution by selecting Recent Projects from the File menu. The «DebuggingExample.sln» solution file will be listed as the most recently used file.
Open Form1 in the Forms Designer and select the DebugControl control.
Change the value of the DemoString property. When you commit the change, the debugging instance of Visual Studio acquires focus and execution stops at your breakpoint. You can single-step through the property accessor just as your would any other code.
To stop debugging, exit the hosted instance of Visual Studio or select the Stop Debugging button in the debugging instance.
Next steps
Now that you can debug your custom controls at design time, there are many possibilities for expanding your control’s interaction with the Visual Studio IDE.
You can use the DesignMode property of the Component class to write code that will only execute at design time. For details, see DesignMode.
There are several attributes you can apply to your control’s properties to manipulate your custom control’s interaction with the designer. You can find these attributes in the System.ComponentModel namespace.
You can write a custom designer for your custom control. This gives you complete control over the design experience using the extensible designer infrastructure exposed by Visual Studio. For details, see Walkthrough: Creating a Windows Forms Control That Takes Advantage of Visual Studio Design-Time Features.