Debugging windows form application

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.

Читайте также:  Установка windows через usb накопитель

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.

Пошаговое руководство. Отладка веб-формы Walkthrough: Debugging a Web Form

Шаги данного руководства иллюстрируют способ отладки веб-приложений ASP.NET ASP.NET , также известных как веб-формы. The steps in this walkthrough show you how to debug an ASP.NET ASP.NET Web application, also known as a Web Form. Оно содержит описание запуска и остановки выполнения, определения точек останова и проверки значений переменных в окне Контрольное значение. It shows you how to start and stop execution, set breakpoints, and examine variables in the Watch window.

Для выполнения данного руководства необходимо обладать правами администратора на сервере. To complete this walkthrough, you must have Administrator privileges on the server computer. По умолчанию процесс ASP.NET ASP.NET , aspnet_wp.exe или w3wp.exe, выполняется как процесс ASP.NET ASP.NET . By default, the ASP.NET ASP.NET process, aspnet_wp.exe or w3wp.exe, runs as an ASP.NET ASP.NET process. Для отладки ASP.NET ASP.NET необходимо обладать правами администратора на компьютере, на котором выполняется ASP.NET ASP.NET . To debug ASP.NET ASP.NET , you must have Administrator privileges on the computer where ASP.NET ASP.NET runs it. Дополнительные сведения см. в статье System Requirements. For more information, see System Requirements.

Отображаемые диалоговые окна и команды меню могут отличаться от описанных в справке в зависимости от действующих параметров или выпуска среды. The dialog boxes and menu commands you see might differ from those described in Help, depending on your active settings or edition. Чтобы изменить параметры, выберите в меню Сервис пункт Импорт и экспорт параметров . To change your settings, choose Import and Export Settings on the Tools menu. Дополнительные сведения см. в разделе Сброс параметров. For more information, see Reset settings.

Создание веб-формы To create the Web Form

Если какое-либо решение уже открыто, закройте его. If you already have a solution open, close it.

В меню Файл выберите пункт Создать и щелкните Веб-сайт. On the File menu, click New, and then click Web Site.

Читайте также:  Что такое сертифицированная windows

Откроется диалоговое окно Новый веб-сайт. The New Web Site dialog box appears.

В области Шаблоны щелкните Веб-сайт ASP.NET. In the Templates pane, click ASP.NET Web Site.

В строке Расположение выберите HTTP в списке и введите в текстовом поле http://localhost/WebSite . On the Location line, click HTTP from the list, and in the text box, type http://localhost/WebSite.

В списке Язык выберите Visual C# или Visual Basic. In the Language list, click Visual C# or Visual Basic.

Нажмите кнопку ОК. Click OK.

Visual Studio Visual Studio создаст новый проект и отобразит исходный код HTML, создаваемый по умолчанию. creates a new project, and displays the default HTML source code. Среда также создаст виртуальный каталог WebSite в разделе Веб-сайт по умолчанию в IIS. It also creates a new virtual directory named WebSite under Default Web Site in IIS.

Щелкните вкладку Конструктор на нижней границе окна. Click the Design tab on the bottom margin.

Щелкните вкладку Панель элементов на левой границе или выберите ее в меню Вид. Click the Toolbox tab on the left margin, or select it on the View menu.

Откроется Панель элементов . The Toolbox opens.

На панели элементов щелкните элемент управления Button и добавьте его в главную рабочую область конструирования Default.aspx. In the Toolbox, click the Button control and add it to the main design surface, Default.aspx.

На панели элементов щелкните элемент управления Textbox и перетащите его в главную рабочую область конструирования Default.aspx. In the Toolbox, click the Textbox control, and drag the control to the main design surface, Default.aspx.

Дважды щелкните сброшенный в конструктор элемент управления Button. Double-click the button control you dropped.

Появится страница кода: Default.aspx.cs для C# или Default.aspx.vb для Visual Basic Visual Basic . This takes you to the code page: Default.aspx.cs for C# or Default.aspx.vb for Visual Basic Visual Basic . Курсор должен находиться в тексте функции Button1_Click . The cursor should be in the function Button1_Click .

В функции Button1_Click добавьте следующий код: In the Button1_Click function, add the following code:

В меню Сборка выберите Собрать решение. On the Build menu, click Build Solution.

Проект должен быть построен без ошибок. The project should build without errors.

Теперь все готово для того, чтобы начать отладку. Now, you are ready to start debugging.

Отладка веб-формы To debug the Web Form

В окне Default.aspx.cs или Default.aspx.vb щелкните левую границу рядом с добавленной текстовой строкой: In the Default.aspx.cs or Default.aspx.vb 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. Если приложение запускается из отладчика, выполнение этого приложения будет приостановлено отладчиком на строке с помеченным кодом. 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. Дополнительные сведения см. в разделе Точки останова. For more information, see Breakpoints.

В меню Отладка щелкните Начать отладку. On the Debug menu, click Start Debugging.

Появляется диалоговое окно Отладка не включена. The Debugging Not Enabled dialog box appears. Выберите параметр Изменить файл web.config для включения отладки и нажмите кнопку ОК. Select Modify the Web.config file to enable debugging option, and click OK.

Читайте также:  The bat windows media

Будет запущен обозреватель Internet Explorer, в котором будет отображена только что созданная страница. Internet Explorer starts and displays the page that you just designed.

Нажмите кнопку в Internet Explorer. In Internet Explorer, click the button.

В Visual Studio Visual Studio будет отображена строка кода в странице кода Default.aspx.cs или Default.aspx.vb, на которой была поставлена точка останова. In Visual Studio Visual Studio , this takes you to the line where you set your breakpoint on the code page Default.aspx.cs or Default.aspx.vb. Эта строка будет выделена желтым цветом. This line should be highlighted in yellow. Теперь можно просматривать переменные в приложении и управлять его выполнением. You can now view the variables in your application and control its execution. После завершения выполнения приложение ожидает команды пользователя. Your application stops executing and waits for a command from you.

В меню Отладка выберите пункт Окна, затем Контрольные значения и Watch1. On the Debug menu, click Windows, then click Watch, and then click Watch1.

В окне Контрольные значения введите TextBox1.Text. In the Watch window, type TextBox1.Text.

Окно Контрольные значения отобразит значение переменной TextBox1.Text : The Watch window shows the value of the variable TextBox1.Text :

В меню Отладка выберите команду Шаг с обходом. On the Debug menu, click Step Over.

Значение TextBox1.Text в окне Контрольные значения изменится на следующее: The value of TextBox1.Text changes in the Watch window to read:

«Button was clicked!»

В меню Отладка выберите команду Продолжить. On the Debug menu, click Continue.

Снова нажмите кнопку в Internet Explorer. In Internet Explorer, click the button again.

Выполнение снова будет приостановлено по достижении точки останова. Execution stops at the breakpoint again.

В окне Default.aspx.cs или Default.aspx.vb щелкните красную точку на левой границе. In the Default.aspx.cs or Default.aspx.vb window, click the red dot in the left margin.

Точка останова будет удалена. This removes the breakpoint.

В меню Отладка щелкните пункт Остановить отладку. On the Debug menu, click Stop Debugging.

Присоединение отладчика к веб-форме To attach to the Web Form for debugging

В Visual Studio Visual Studio можно присоединить отладчик к выполняющемуся процессу. In Visual Studio Visual Studio , you can attach the debugger to a running process. Для повышения эффективности отладки скомпилируйте исполняемый файл как отладочную версию с файлами символов (PDB). For most effective debugging, compile the executable as a Debug version with symbol (PDB) files.

В окне Default.aspx.cs или Default.aspx.vb щелкните левую границу, чтобы снова создать точку останова на добавленной строке: In the Default.aspx.cs or Default.aspx.vb window, click in the left margin to again set a breakpoint at the line you added:

В меню Отладка выберите команду Начать без отладки. On the Debug menu, click Start Without Debugging.

Веб-форма будет запущена в Internet Explorer без присоединения отладчика. The Web Form starts to run under Internet Explorer, but the debugger is not attached.

Присоединитесь к процессу ASP.NET ASP.NET . Attach to the ASP.NET ASP.NET process. Дополнительные сведения см. в разделе Отладка развернутых веб-приложений. For more information, see Debugging Deployed Web Applications.

Нажмите кнопку в форме в обозревателе Internet Explorer. In Internet Explorer, click the button on your form.

В Visual Studio Visual Studio при этом должен произойти переход на точку останова на странице кода Default.aspx.cs, Default.aspx.vb или Default.aspx. In Visual Studio Visual Studio , you should hit the breakpoint in Default.aspx.cs, Default.aspx.vb, or Default.aspx.

После завершения отладки в меню Отладка выберите команду Остановить отладку. When you are finished debugging, on the Debug menu, click Stop Debugging.

Оцените статью