- Debugging Preparation: Windows Forms Applications
- Configuration Properties in Debug tab
- To debug a C#, F#, or Visual Basic Windows Forms application
- Пошаговое руководство. Отладка формы 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: Debugging a Windows Form
- To prepare for this walkthrough
- Create a New Windows Form
- To create the Windows form for this walkthrough
- Debug Your Form
- To debug the Windows Form created for this walkthrough
- Attach to Your Windows Form Application for Debugging
- To attach to the Windows Form Application for debugging
Debugging Preparation: Windows Forms Applications
The Windows Forms App project template creates a Windows Forms application. Debugging this type of application in Visual Studio is straightforward. For information on creating a project of this type, see Create a Windows Form App.
When you create a Windows Forms project with the project template, Visual Studio automatically creates required settings for the Debug and Release configurations. If necessary, you can change these settings. These settings can be changed in the
Property Pages dialog box (My Project in Visual Basic).
The following table displays one additional recommended property setting.
Configuration Properties in Debug tab
Property Name | Setting |
---|---|
Start Action | — Set to Start project, most of the time. Set to Start external program if you want to start another executable when you start debugging (usually for debugging DLLs). |
You can debug Windows Forms applications from inside Visual Studio, or by attaching to an already running application. For more information about attaching, see Attach to Running Processes.
To debug a C#, F#, or Visual Basic Windows Forms application
Open the project in Visual Studio.
Create breakpoints as needed.
Because Windows Forms applications are event-driven, your breakpoints will go into event handler code, or into methods called by event handler code. Typical events in which to place breakpoints include:
Events associated with a control, such as Click, Enter, etc.
Events associated with application startup and shutdown, such as Load, Activated, etc.
Focus and Validation Events.
On the Debug menu, click Start.
Debug using the techniques discussed in First look at the debugger.
Пошаговое руководство. Отладка формы 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: Debugging a Windows Form
A Windows Form is one of the most common managed applications. A Windows Form creates a standard Windows application. 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.)
Create a New Windows Form
Next, you will create a new Windows Form.
To create the Windows form for this walkthrough
On the File menu, choose New and click Project.
The New Project dialog box appears.
In the Project Types pane, open the Visual Basic, Visual C#, or Visual C++ node, then
For Visual Basic or Visual C#, select Windows Desktop > Windows Form App.
For Visual C++, select Windows Desktop Application.
In the Name box, give the project a unique name (for example, Walkthrough_SimpleDebug).
Click OK.
Visual Studio creates a new project and displays a new form in the Windows Forms designer. 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. The cursor should be in 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.
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.
The Windows Form starts running.
On the Windows Form, click the button you added.
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.
On the Debug menu, choose Windows, then Watch, and click Watch1.
In the Watch1 window, click on a blank row. 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.
The Watch1 window shows the value of this variable in quotation marks as:
On the Debug menu, choose Step Into.
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.
On the Windows Form, click the button again.
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.
Attach to Your Windows Form Application for Debugging
In Visual Studio, you can attach the debugger to a running process. If you are using an Express Edition, this feature is not supported.
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.
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.
In the Available Processes pane, find the process name (Walkthrough_SimpleDebug.exe) in the Process column and click it.
Click the Attach button.
In your Windows Form, click the one and only button.
The debugger breaks execution of the Windows Form at the breakpoint.