Command line windows application

How to: Create a Windows Forms application from the command line

The following procedures describe the basic steps that you must complete to create and run a Windows Forms application from the command line. There is extensive support for these procedures in Visual Studio. Also see Walkthrough: Hosting a Windows Forms Control in WPF.

Procedure

To create the form

In an empty code file, type the following Imports or using statements:

Declare a class named Form1 that inherits from the Form class:

Create a parameterless constructor for Form1 .

You will add more code to the constructor in a subsequent procedure.

Add a Main method to the class.

Apply the STAThreadAttribute to the C# Main method to specify your Windows Forms application is a single-threaded apartment. (The attribute is not necessary in Visual Basic, since Windows forms applications developed with Visual Basic use a single-threaded apartment model by default.)

Call EnableVisualStyles to apply operating system styles to your application.

Create an instance of the form and run it.

To compile and run the application

At the .NET Framework command prompt, navigate to the directory you created the Form1 class.

Compile the form.

If you are using C#, type: csc form1.cs

If you are using Visual Basic, type: vbc form1.vb

At the command prompt, type: Form1.exe

Adding a control and handling an event

The previous procedure steps demonstrated how to just create a basic Windows Form that compiles and runs. The next procedure will show you how to create and add a control to the form, and handle an event for the control. For more information about the controls you can add to Windows Forms, see Windows Forms Controls.

In addition to understanding how to create Windows Forms applications, you should understand event-based programming and how to handle user input. For more information, see Creating Event Handlers in Windows Forms, and Handling User Input

To declare a button control and handle its click event

Declare a button control named button1 .

In the constructor, create the button and set its Size, Location and Text properties.

Add the button to the form.

The following code example demonstrates how to declare the button control:

Create a method to handle the Click event for the button.

In the click event handler, display a MessageBox with the message, «Hello World».

The following code example demonstrates how to handle the button control’s click event:

Associate the Click event with the method you created.

The following code example demonstrates how to associate the event with the method.

Compile and run the application as described in the previous procedure.

Example

The following code example is the complete example from the previous procedures:

Аргументы командной строки (Руководство по программированию на C#) Command-Line Arguments (C# Programming Guide)

Вы можете передавать аргументы в метод Main , определив метод одним из следующих способов: You can send arguments to the Main method by defining the method in one of the following ways:

Код метода Main Main method code Сигнатура Main Main signature
Без возвращаемого значения, без использования await No return value, no use of await static void Main(string[] args)
С возвращаемым значением, без использования await Return value, no use of await static int Main(string[] args)
Без возвращаемого значения, с использованием await No return value, uses await static async Task Main(string[] args)
С возвращаемым значением, с использованием await Return value, uses await static async Task Main(string[] args)

Если аргументы не используются, можно опустить args в сигнатуре метода, чтобы немного упростить код: If the arguments are not used, you can omit args from the method signature for slightly simpler code:

Код метода Main Main method code Сигнатура Main Main signature
Без возвращаемого значения, без использования await No return value, no use of await static void Main()
С возвращаемым значением, без использования await Return value, no use of await static int Main()
Без возвращаемого значения, с использованием await No return value, uses await static async Task Main()
С возвращаемым значением, с использованием await Return value, uses await static async Task Main()

Чтобы включить аргументы командной строки в методе Main в приложении Windows Forms, необходимо вручную изменить сигнатуру Main в файле program.cs. To enable command-line arguments in the Main method in a Windows Forms application, you must manually modify the signature of Main in program.cs. Код, созданный с помощью конструктора Windows Forms, создает Main без входного параметра. The code generated by the Windows Forms designer creates a Main without an input parameter. Также можно использовать Environment.CommandLine или Environment.GetCommandLineArgs для доступа к аргументам командной строки из любой точки в консоли или приложении Windows. You can also use Environment.CommandLine or Environment.GetCommandLineArgs to access the command-line arguments from any point in a console or Windows application.

Параметр метода Main — это массив String, представляющий аргументы командной строки. The parameter of the Main method is a String array that represents the command-line arguments. Как правило, определить, существуют ли аргументы, можно, проверив свойство Length , например: Usually you determine whether arguments exist by testing the Length property, for example:

Массив args не может иметь значение NULL. The args array cannot be null. Поэтому доступ к свойству Length можно получить без проверки значения NULL. So, it’s safe to access the Length property without null checking.

Строковые аргументы также можно преобразовать в числовые типы с помощью класса Convert или метода Parse . You can also convert the string arguments to numeric types by using the Convert class or the Parse method. Например, следующая инструкция преобразует string в число long с помощью метода Parse: For example, the following statement converts the string to a long number by using the Parse method:

Можно также использовать тип C# long , который является псевдонимом Int64 : It is also possible to use the C# type long , which aliases Int64 :

Кроме того, можно использовать метод класса Convert , ToInt64 : You can also use the Convert class method ToInt64 to do the same thing:

Дополнительные сведения см. в разделах Parse и Convert. For more information, see Parse and Convert.

Пример Example

В следующем примере показано использование аргументов командной строки в консольном приложении. The following example shows how to use command-line arguments in a console application. Приложение принимает один аргумент времени выполнения, преобразует аргумент в целое число и вычисляет факториал числа. The application takes one argument at run time, converts the argument to an integer, and calculates the factorial of the number. Если не указано никаких аргументов, приложение выдает сообщение, поясняющее правильное использование программы. If no arguments are supplied, the application issues a message that explains the correct usage of the program.

Чтобы скомпилировать и запустить приложение из командной строки, выполните следующие действия. To compile and run the application from a command prompt, follow these steps:

Вставьте следующий код в любой текстовый редактор и сохраните файл как текстовый файл с именем Factorial.cs. Paste the following code into any text editor, and then save the file as a text file with the name Factorial.cs.

На начальном экране или в меню Пуск откройте окно командной строки разработчика Visual Studio и перейдите к папке, содержащей файл, который вы только что создали. From the Start screen or Start menu, open a Visual Studio Developer Command Prompt window, and then navigate to the folder that contains the file that you just created.

Введите следующую команду для компиляции приложения. Enter the following command to compile the application.

Если для приложения не выдаются ошибки компиляции, создается исполняемый файл с именем Factorial.exe. If your application has no compilation errors, an executable file that’s named Factorial.exe is created.

Введите приведенную ниже команду для вычисления факториала числа 3: Enter the following command to calculate the factorial of 3:

Код создает следующие выходные данные: The factorial of 3 is 6. The command produces this output: The factorial of 3 is 6.

При выполнении приложения в Visual Studio аргументы командной строки можно указать на странице «Отладка» в конструкторе проектов. When running an application in Visual Studio, you can specify command-line arguments in the Debug Page, Project Designer.

Самые используемые команды запуска приложений из командной строки.

Пуск -> Выполнить или win+R:

Команды для запуска элементов управления:

  • Сетевые подключения: ncpa.cpl
  • Свойства системы: sysdm.cpl
  • Установка и удаление программ: appwiz.cpl
  • Учетные записи пользователей: nusrmgr.cpl
  • Дата и время: timedate.cpl
  • Свойства экрана: desk.cpl
  • Брэндмауэр Windows: firewall.cpl
  • Мастер установки оборудования: hdwwiz.cpl
  • Свойства Интернет: inetcpl.cpl
  • Специальные возможности: access.cpl
  • Свойства мыши: control Main.cpl
  • Свойства клавиатуры: control Main.cpl,@1
  • Язык и региональные возможности: intl.cpl
  • Игровые устройства: joy.cpl
  • Свойства: Звуки и аудиоустройства: mmsys.cpl
  • Мастер настройки сети: netsetup.cpl
  • Управление электропитанием: powercfg.cpl
  • Центр обеспечения безопасности: wscui.cpl
  • Автоматическое обновление: wuaucpl.cpl
  • control — Панель управления
  • control admintools — Администрирование
  • control desktop — Настройки экрана / Персонализация
  • control folders — Свойства папок
  • control fonts — Шрифты
  • control keyboard — Свойства клавиатуры
  • control mouse — Свойства мыши
  • control printers — Устройства и принтеры
  • control schedtasks — Планировщик заданий

Запускать из окружения пользователя, от другого имени, можно запускать большинство элементов управления, кроме тех, которые используют explorer. Например Панель «Сетевые подключения» использует explorer.

Команды windows для запуска оснасток

  • Управление компьютером (Computer Management): compmgmt.msc
  • Редактор объектов локальной политики (Group Policy Object Editor): gpedit.msc
  • Результирующая политика (результат применения политик): rsop.msc
  • Службы (Services): services.msc
  • Общие папки (Shared Folders): fsmgmt.msc
  • Диспетчер устройств (Device Manager): devmgmt.msc
  • Локальные пользователи и группы (Local users and Groups): lusrmgr.msc
  • Локальная политика безопасности (Local Security Settings): secpol.msc
  • Управление дисками (Disk Management): diskmgmt.msc
  • eventvwr.msc: Просмотр событий
  • certmgr.msc: Сертификаты — текущий пользователь
  • tpm.msc — управление доверенным платформенным модулем (TPM) на локальном компьютере.

«Серверные» оснастки:

  • Active Directory Пользователи и компьютеры (AD Users and Computers): dsa.msc
  • Диспетчер служб терминалов (Terminal Services Manager): tsadmin.msc
  • Консоль управления GPO (Group Policy Management Console): gpmc.msc
  • Настройка терминального сервера (TS Configuration): tscc.msc
  • Маршрутизация и удаленый доступ (Routing and Remote Access): rrasmgmt.msc
  • Active Directory Домены и Доверие (AD Domains and Trusts): domain.msc
  • Active Directory Сайты и Доверие (AD Sites and Trusts): dssite.msc
  • Политика безопасности домена (Domain Security Settings): dompol.msc
  • Политика безопасности контроллера домена (DC Security Settings): dcpol.msc
  • Распределенная файловая система DFS (Distributed File System): dfsgui.msc

Остальные команды windows:

  • calc — Калькулятор
  • charmap — Таблица символов
  • chkdsk — Утилита для проверки дисков
  • cleanmgr — Утилита для очистки дисков
  • cmd — Командная строка
  • dfrgui — Дефрагментация дисков
  • dxdiag — Средства диагностики DirectX
  • explorer — Проводник Windows
  • logoff — Выйти из учетной записи пользователя Windows
  • magnify — Лупа (увеличительное стекло)
  • msconfig — Конфигурация системы
  • msinfo32 — Сведения о системе
  • mspaint — Графический редактор Paint
  • notepad — Блокнот
  • osk — Экранная клавиатура
  • perfmon — Системный монитор
  • regedit — Редактор реестра
  • shutdown — Завершение работы Windows
  • syskey — Защита БД учетных записей Windows
  • taskmgr — Диспетчер задач
  • utilman — Центр специальных возможностей
  • verifier — Диспетчер проверки драйверов
  • winver — Версия Windows
  • write — Редактор Wordpad
  • whoami — отобразит имя текущего пользователя
  • powercfg /requests — команда сообщит какие процессы, сервисы или драйверы не дают уходить системе в спящий режим. Начиная с windows 7
  • wuauclt /detectnow — проверить наличие обновлений
  • wuauclt /reportnow — отправить на сервер информацию о установленных обновлениях
  • gpupdate /force — обновление политик
  • gpresult — просмотр того, какие политики применились на компьютере
    • gpresult /H GPReport.html — в виде детального html отчета
    • gpresult /R — отобразить сводную информации в командной строке
    • gpresult /R /V — Отображение подробной информации. Подробная информация содержит сведения о параметрах, примененных с приоритетом 1.
  • mountvol — список подключенных томов
  • mstsc /v:198.162.0.1 — подключение к удаленному рабочему столу компьютера 198.162.0.1
  • wmic — команда упрощающая использование инструментария управления Windows (WMI) и систем, управляемых с помощью WMI (как на локальных, так и на удаленных компьютерах). Пример:
    • wmic logicaldisk where drivetype=2 get deviceid, volumename, description — список логических томов типа 2 (Removable Disk)
    • wmic process where (name LIKE ‘c%’) get name, processid — выводим имя и id процессов, которые начинаются с символа «c»
    • wmic process get /? или wmic process /? или wmic /? — справка
    • wmic process where (name LIKE ‘x%’) call terminate(0) — завершили процессы начинающиеся на букву «x»
  • msra.exe /offerra — удаленный помощник
  • slui 4 — вызов активации по телефону. Мне помогло, когда при попытке активации Windows Server 2008 SP2 я получал ошибку «activation error code 0×8004FE92» и при этом не было доступного варианта «активация по телефону»
  • MdSched.exe — диагностика оперативной памяти в Windows, аля memtest
  • 25 самых больших папок на диске C: (работает начиная с windows 8): dfp /b /top 25 /elapsed /study C:\
  • 25 самых больших файлов в папке c:\temp — Powershell «Get-ChildItem c:\temp -recurse | Sort-Object length -descending | select-object -first 32 | ft name,length -wrap –auto»
  • Отключение сообщения в журнале Windows — Безопасность: «Платформа фильтрации IP-пакетов Windows разрешила подключение»:
  • Просмотр текущей политики аудита системы:

Команды windows для настройки сети

  • proxycfg -? — инструмент настройки прокси по умолчанию в Windows XP/2003, WinHTTP.
  • netsh winhttp — инструмент настройки прокси по умолчанию в Windows Vista/7/2008
  • netsh interface ip show config — посмотреть конфигурацию интерфейсов
  • Настраиваем интерфейс «Local Area Connection» — IP, маска сети, шлюз:

netsh interface ip set address name=»Local Area Connection» static 192.168.1.100 255.255.255.0 192.168.1.1 1

  • netsh -c interface dump > c:\conf.txt — экспорт настроек интерфейсов
  • netsh -f c:\conf.txt — импорт настроек интерфейсов
  • netsh exec c:\conf.txt — импорт настроек интерфейсов
  • netsh interface ip set address «Ethernet» dhcp — включить dhcp
  • netsh interface ip set dns «Ethernet» static 8.8.8.8 — переключаем DNS на статику и указываем основной DNS-сервер
  • netsh interface ip set wins «Ethernet» static 8.8.8.8 — указываем Wins сервер
  • netsh interface ip add dns «Ethernet» 8.8.8.8 index=1 — задаем первичный dns
  • netsh interface ip add dns «Ethernet» 8.8.4.4 index=2 — задаем вторичный dns
  • netsh interface ip set dns «Ethernet» dhcp — получаем DNS по DHCP

Команды для установки, просмотра, удаления программ и обновлений

  • Запуск msi пакетов из командной строки под правами администратора:
  • wmic product get name,version,vendor — просмотр установленных программ (только установленные из msi-пакетов)
  • wmic product where name=»Имя программы» call uninstall /nointeractive — удаление установленной программы
  • Get-WmiObject Win32_Product | ft name,version,vendor,packagename — просмотр установленных программ через Powershell (только установленные из msi-пакетов)
  • (Get-WmiObject Win32_Product -Filter «Name = ‘Имя программы’»).Uninstall() — удаление установленной программы через Powershell
  • DISM /Image:D:\ /Get-Packages — просмотр установленных обновлений из загрузочного диска
  • DISM /Online /Get-Packages — просмотру установленных обновлений на текущей ОС
  • DISM /Image:D:\ /Remove-Package /PackageName:Package_for_KB3045999

6.1.1.1 — удаление обновления из загрузочного диска
DISM /Online /Remove-Package /PackageName:Package_for_KB3045999

6.1.1.1 — удаление обновления в текущей ОС

Читайте также:  Настройки почты яндекс imap mac os
Оцените статью