Debug windows forms application

Содержание
  1. How to: Debug Windows Service Applications
  2. To debug a service
  3. Debugging Tips for Windows Services
  4. How to: Run a Windows Service as a console application
  5. Подготовка к отладке: Приложения Windows Forms Debugging Preparation: Windows Forms Applications
  6. «Свойства конфигурации» во вкладке «Отладка» Configuration Properties in Debug tab
  7. Выполнение отладки приложения Windows Forms на C#, F# или Visual Basic To debug a C#, F#, or Visual Basic Windows Forms application
  8. Пошаговое руководство. Отладка формы Windows Form Walkthrough: Debugging a Windows Form
  9. Чтобы подготовиться к выполнению данного пошагового руководства To prepare for this walkthrough
  10. Создание новой формы Windows Forms. Create a New Windows Form
  11. Чтобы создать форму Windows Forms для данного примера To create the Windows form for this walkthrough
  12. Отладка формы Debug Your Form
  13. Чтобы выполнить отладку формы Windows Forms, созданной для данного примера To debug the Windows Form created for this walkthrough
  14. Присоединение к приложению Windows Form для отладки Attach to Your Windows Form Application for Debugging
  15. Присоединение к приложению Windows Form для отладки To attach to the Windows Form Application for debugging

How to: Debug Windows Service Applications

A service must be run from within the context of the Services Control Manager rather than from within Visual Studio. For this reason, debugging a service is not as straightforward as debugging other Visual Studio application types. To debug a service, you must start the service and then attach a debugger to the process in which it is running. You can then debug your application by using all of the standard debugging functionality of Visual Studio.

You should not attach to a process unless you know what the process is and understand the consequences of attaching to and possibly killing that process. For example, if you attach to the WinLogon process and then stop debugging, the system will halt because it can’t operate without WinLogon.

You can attach the debugger only to a running service. The attachment process interrupts the current functioning of your service; it doesn’t actually stop or pause the service’s processing. That is, if your service is running when you begin debugging, it is still technically in the Started state as you debug it, but its processing has been suspended.

After attaching to the process, you can set breakpoints and use these to debug your code. Once you exit the dialog box you use to attach to the process, you are effectively in debug mode. You can use the Services Control Manager to start, stop, pause and continue your service, thus hitting the breakpoints you’ve set. You can later remove this dummy service after debugging is successful.

This article covers debugging a service that’s running on the local computer, but you can also debug Windows Services that are running on a remote computer. See Remote Debugging.

Debugging the OnStart method can be difficult because the Services Control Manager imposes a 30-second limit on all attempts to start a service. For more information, see Troubleshooting: Debugging Windows Services.

To get meaningful information for debugging, the Visual Studio debugger needs to find symbol files for the binaries that are being debugged. If you are debugging a service that you built in Visual Studio, the symbol files (.pdb files) are in the same folder as the executable or library, and the debugger loads them automatically. If you are debugging a service that you didn’t build, you should first find symbols for the service and make sure they can be found by the debugger. See Specify Symbol (.pdb) and Source Files in the Visual Studio Debugger. If you’re debugging a system process or want to have symbols for system calls in your services, you should add the Microsoft Symbol Servers. See Debugging Symbols.

To debug a service

Build your service in the Debug configuration.

Install your service. For more information, see How to: Install and Uninstall Services.

Start your service, either from Services Control Manager, Server Explorer, or from code. For more information, see How to: Start Services.

Start Visual Studio with administrative credentials so you can attach to system processes.

(Optional) On the Visual Studio menu bar, choose Tools, Options. In the Options dialog box, choose Debugging, Symbols, select the Microsoft Symbol Servers check box, and then choose the OK button.

On the menu bar, choose Attach to Process from the Debug or Tools menu. (Keyboard: Ctrl+Alt+P)

The Processes dialog box appears.

Select the Show processes from all users check box.

In the Available Processes section, choose the process for your service, and then choose Attach.

The process will have the same name as the executable file for your service.

The Attach to Process dialog box appears.

Choose the appropriate options, and then choose OK to close the dialog box.

Читайте также:  Монитор для рисования от windows

You are now in debug mode.

Set any breakpoints you want to use in your code.

Access the Services Control Manager and manipulate your service, sending stop, pause, and continue commands to hit your breakpoints. For more information about running the Services Control Manager, see How to: Start Services. Also, see Troubleshooting: Debugging Windows Services.

Debugging Tips for Windows Services

Attaching to the service’s process allows you to debug most, but not all, the code for that service. For example, because the service has already been started, you cannot debug the code in the service’s OnStart method or the code in the Main method that is used to load the service this way. One way to work around this limitation is to create a temporary second service in your service application that exists only to aid in debugging. You can install both services, and then start this dummy service to load the service process. Once the temporary service has started the process, you can use the Debug menu in Visual Studio to attach to the service process.

Try adding calls to the Sleep method to delay action until you’re able to attach to the process.

Try changing the program to a regular console application. To do this, rewrite the Main method as follows so it can run both as a Windows Service and as a console application, depending on how it’s started.

How to: Run a Windows Service as a console application

Add a method to your service that runs the OnStart and OnStop methods:

Rewrite the Main method as follows:

In the Application tab of the project’s properties, set the Output type to Console Application.

Choose Start Debugging (F5).

To run the program as a Windows Service again, install it and start it as usual for a Windows Service. It’s not necessary to reverse these changes.

In some cases, such as when you want to debug an issue that occurs only on system startup, you have to use the Windows debugger. Download the Windows Driver Kit (WDK) and see How to debug Windows Services.

Подготовка к отладке: Приложения Windows Forms Debugging Preparation: Windows Forms Applications

Шаблон проекта приложения Windows Forms создает приложение Windows Forms. The Windows Forms App project template creates a Windows Forms application. Отладка приложений такого типа в Visual Studio Visual Studio не вызывает никаких затруднений. Debugging this type of application in Visual Studio Visual Studio is straightforward. Сведения о создании проекта этого типа см. в статье Создание приложения Windows Forms на C# в Visual Studio. For information on creating a project of this type, see Create a Windows Form App.

При создании проекта Windows Forms из шаблона проекта, Visual Studio Visual Studio автоматически создает требуемые параметры для отладки и выпуска. When you create a Windows Forms project with the project template, Visual Studio Visual Studio automatically creates required settings for the Debug and Release configurations. При необходимости эти параметры можно изменить. If necessary, you can change these settings. Эти параметры могут быть изменены в диалоговом окне

Страницы свойств (Мой проект в Visual Basic). These settings can be changed in the

Property Pages dialog box (My Project in Visual Basic).

Дополнительные сведения см. в статье Рекомендуемые параметры свойств. For more information, see Recommended Property Settings.

В следующей таблице приведены дополнительные параметры, рекомендуемые к использованию. 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. Установите Запуск внешней программы, если требуется запускать другой исполняемый файл при запуске отладки (обычно для отладки DLL). Set to Start external program if you want to start another executable when you start debugging (usually for debugging DLLs).

Можно выполнять отладку приложений Windows Forms из Visual Studio Visual Studio или путем присоединения к уже запущенному приложению. You can debug Windows Forms applications from inside Visual Studio Visual Studio , or by attaching to an already running application. См. сведения о присоединении к выполняемым процессам. For more information about attaching, see Attach to Running Processes.

Выполнение отладки приложения Windows Forms на C#, F# или Visual Basic To debug a C#, F#, or Visual Basic Windows Forms application

Откройте проект в Visual Studio Visual Studio . Open the project in Visual Studio Visual Studio .

Создайте точки останова, если требуется. Create breakpoints as needed.

Поскольку приложения Windows Forms управляются событиями, точки останова появятся в коде обработчиков событий, или в методах, вызываемых ими. 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:

события, связанные с элементом управления, такие как Click, Enter, и т.д.; Events associated with a control, such as Click, Enter, etc.

события, связанные с запуском приложений и завершением работы, такие как Load, Activated и т. д.; 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.

Читайте также:  Заменить просроченный пароль windows
Оцените статью