- Как добавить форму в проект (Windows Forms .NET) How to add a form to a project (Windows Forms .NET)
- Добавление новой формы Add a new form
- Добавление ссылки на проект в форму Add a project reference to a form
- c# open a new form then close the current form?
- 15 Answers 15
- Пошаговое руководство. получение данных с помощью формы Windows Walkthrough: Collect data by using a Windows Form
- Предварительные требования Prerequisites
- Создание нового проекта Create a new project
- Создание нового проекта To create a new project
- Добавление элемента управления NamedRange на лист Add a NamedRange control to the worksheet
- Добавление именованного диапазона в Sheet1 To add a named range to Sheet1
- Добавление формы Windows Forms в проект Add a Windows Form to the project
- Добавление формы Windows Forms To add a Windows Form
- Отображение Windows Form и сбор сведений Display the Windows Form and collecting information
- Отображение формы и сбор информации To display the form and collect information
- Отправка сведений на лист Send information to the worksheet
- Отправка информации в лист To send information to the worksheet
- Тест Test
- Проверка книги To test your workbook
- Дальнейшие действия Next steps
Как добавить форму в проект (Windows Forms .NET) How to add a form to a project (Windows Forms .NET)
Добавьте формы в свой проект с помощью Visual Studio. Add forms to your project with Visual Studio. Если в приложении несколько форм, вы сможете выбрать начальную форму для приложения или одновременно отобразить несколько форм. When your app has multiple forms, you can choose which is the startup form for your app, and you can display multiple forms at the same time.
Документация для Руководства по рабочему столу по .NET 5 (и .NET Core) находится в разработке. The Desktop Guide documentation for .NET 5 (and .NET Core) is under construction.
Добавление новой формы Add a new form
Добавьте новую форму в Visual Studio. Add a new form with Visual Studio.
В Visual Studio найдите панель Обозреватель проектов. In Visual Studio, find the Project Explorer pane. Щелкните проект правой кнопкой мыши и выберите Добавить > Форма (Windows Forms) . Right-click on the project and choose Add > Form (Windows Forms).
В поле Имя введите имя формы, например MyNewForm. In the Name box, type a name for your form, such as MyNewForm. Visual Studio сформирует имя по умолчанию, которое является уникальным. Можно использовать это имя. Visual Studio will provide a default and unique name that you may use.
После добавления формы Visual Studio откроет конструктор форм для этой формы. Once the form has been added, Visual Studio opens the form designer for the form.
Добавление ссылки на проект в форму Add a project reference to a form
Если у вас есть исходные файлы для формы, можно добавить форму в проект, скопировав файлы в папку проекта. If you have the source files to a form, you can add the form to your project by copying the files into the same folder as your project. Ссылки на все файлы кода в папке проекта и в дочерних папках проекта будут автоматически добавлены в проект. The project automatically references any code files that are in the same folder or child folder of your project.
Форма включает два файла с одинаковыми именами и разными расширениями: form2.cs (form2 — пример имени файла) и form2.Designer.cs. Forms are made up of two files that share the same name: form2.cs (form2 being an example of a file name) and form2.Designer.cs. Иногда присутствует файл ресурсов с тем же именем — form2.resx. Sometimes a resource file exists, sharing the same name, form2.resx. В предыдущем примере form2 представляет собой базовое имя файла. In in the previous example, form2 represents the base file name. Необходимо скопировать все связанные файлы в папку проекта. You’ll want to copy all related files to your project folder.
Кроме того, можно использовать Visual Studio для импорта файла в проект. Alternatively, you can use Visual Studio to import a file into your project. При добавлении существующего файла в проект файл копируется в папку проекта. When you add an existing file to your project, the file is copied into the same folder as your project.
В Visual Studio найдите панель Обозреватель проектов. In Visual Studio, find the Project Explorer pane. Щелкните проект правой кнопкой мыши и выберите Добавить > Существующий элемент. Right-click on the project and choose Add > Existing Item.
Перейдите в папку, содержащую файлы формы. Navigate to the folder containing your form files.
c# open a new form then close the current form?
For example, Assume that I’m in form 1 then I want:
- Open form 2( from a button in form 1)
- Close form 1
- Focus on form 2
15 Answers 15
Steve’s solution does not work. When calling this.Close(), current form is disposed together with form2. Therefore you need to hide it and set form2.Closed event to call this.Close().
Many different ways have already been described by the other answers. However, many of them either involved ShowDialog() or that form1 stay open but hidden. The best and most intuitive way in my opinion is to simply close form1 and then create form2 from an outside location (i.e. not from within either of those forms). In the case where form1 was created in Main , form2 can simply be created using Application.Run just like form1 before. Here’s an example scenario:
I need the user to enter their credentials in order for me to authenticate them somehow. Afterwards, if authentication was successful, I want to show the main application to the user. In order to accomplish this, I’m using two forms: LogingForm and MainForm . The LoginForm has a flag that determines whether authentication was successful or not. This flag is then used to decide whether to create the MainForm instance or not. Neither of these forms need to know about the other and both forms can be opened and closed gracefully. Here’s the code for this:
Пошаговое руководство. получение данных с помощью формы Windows Walkthrough: Collect data by using a Windows Form
В этом пошаговом руководстве показано, как открывается форма Windows Forms из настройки уровня документа для Microsoft Office Excel, выполняется сбор сведений от пользователя и запись этих сведений в ячейку листа. This walkthrough demonstrates how to open a Windows Form from a document-level customization for Microsoft Office Excel, collect information from the user, and write that information into a worksheet cell.
Применимо к: Сведения в этом разделе относятся к — проектам уровня документа и добавлению VSTO — в проектах. Applies to: The information in this topic applies to document-level projects and VSTO Add-in projects. См. раздел функции, доступные по типам приложений Office и проектов. See Features available by Office application and project type.
Хотя в этом пошаговом руководстве используется проект уровня документа для Excel, рассмотренная процедура также применима и к другим проектам Office. Although this walkthrough uses a document-level project for Excel specifically, the concepts demonstrated by the walkthrough are applicable to other Office projects.
Предварительные требования Prerequisites
Для выполнения этого пошагового руководства требуются следующие компоненты: You need the following components to complete this walkthrough:
Выпуск Visual Studio, включающий инструменты разработчика Microsoft Office. An edition of Visual Studio that includes the Microsoft Office developer tools. Дополнительные сведения см. в статье Настройка компьютера для разработки решений Office. For more information, see Configure a computer to develop Office solutions.
Excel 2013 Excel 2013 или Excel 2010 Excel 2010 . or Excel 2010 Excel 2010 .
Отображаемые на компьютере имена или расположения некоторых элементов пользовательского интерфейса Visual Studio могут отличаться от указанных в следующих инструкциях. Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. Это зависит от имеющегося выпуска Visual Studio и используемых параметров. The Visual Studio edition that you have and the settings that you use determine these elements. Дополнительные сведения см. в разделе Персонализация интегрированной среды разработки Visual Studio. For more information, see Personalize the Visual Studio IDE.
Создание нового проекта Create a new project
Первым шагом является создание проекта книги Excel. The first step is to create an Excel Workbook project.
Создание нового проекта To create a new project
Создайте проект книги Excel с именем WinFormInput и выберите в мастере Создать новый документ . Create an Excel Workbook project with the name WinFormInput, and select Create a new document in the wizard. Дополнительные сведения см. в разделе как создавать проекты Office в Visual Studio. For more information, see How to: create Office projects in Visual Studio.
Visual Studio открывает новую книгу Excel в конструкторе и добавляет проект WinFormInput в обозреватель решений. Visual Studio opens the new Excel workbook in the designer and adds the WinFormInput project to Solution Explorer.
Добавление элемента управления NamedRange на лист Add a NamedRange control to the worksheet
Добавление именованного диапазона в Sheet1 To add a named range to Sheet1
Выберите ячейку A1 в Sheet1 . Select cell A1 on Sheet1 .
В поле Имя введите formInput. In the Name box, type formInput.
Поле Имя находится слева от строки формул над столбцом A листа. The Name box is located to the left of the formula bar, just above column A of the worksheet.
Нажмите клавишу ВВОД. Press Enter.
Элемент управления NamedRange добавляется в ячейку A1. A NamedRange control is added to cell A1. Видимые изменения на листе отсутствуют, но значение formInput появляется в поле Имя (над листом слева) и в окне Свойства при выборе ячейки A1 . There is no visible indication on the worksheet, but formInput appears in the Name box (just above the worksheet on the left side) and in the Properties window when cell A1 is selected.
Добавление формы Windows Forms в проект Add a Windows Form to the project
Создайте форму Windows Form, чтобы запрашивать сведения у пользователя. Create a Windows Form to prompt the user for information.
Добавление формы Windows Forms To add a Windows Form
Выберите проект WinFormInput в обозревателе решений. Select the project WinFormInput in Solution Explorer.
В меню Проект выберите пункт Добавить форму Windows. On the Project menu, click Add Windows Form.
Дайте этой форме имя GetInputString.vb или GetInputString.cs, а затем нажмите кнопку Добавить. Name the form GetInputString.vb or GetInputString.cs, and then click Add.
Новая форма откроется в конструкторе. The new form opens in the designer.
Добавьте в форму TextBox и Button . Add a TextBox and a Button to the form.
Выберите кнопку, найдите свойство Текст в окне Свойства и измените текст на ОК. Select the button, find the property Text in the Properties window, and change the text to OK.
Затем добавьте в ThisWorkbook.vb или ThisWorkbook.cs код для сбора информации от пользователя. Next, add code to ThisWorkbook.vb or ThisWorkbook.cs to collect the user’s information.
Отображение Windows Form и сбор сведений Display the Windows Form and collecting information
Создайте экземпляр формы Windows GetInputString и отобразите его, а затем запишите информацию от пользователя в ячейку листа. Create an instance of the GetInputString Windows Form and display it, and then write the user’s information into a cell in the worksheet.
Отображение формы и сбор информации To display the form and collect information
Щелкните правой кнопкой мыши файл ThisWorkbook.vb или ThisWorkbook.cs в обозревателе решений, а затем нажмите кнопку Просмотр кода. Right-click ThisWorkbook.vb or ThisWorkbook.cs in Solution Explorer, and then click View Code.
В обработчике событий Open ThisWorkbook добавьте следующий код для объявления переменной формы GetInputString , а затем отобразите эту форму. In the Open event handler of ThisWorkbook , add the following code to declare a variable for the form GetInputString and then show the form.
В C# необходимо добавить обработчик событий, как показано в событии Startup ниже. In C#, you must add an event handler as shown in the Startup event below. Дополнительные сведения о создании обработчиков событий см. в разделе как создавать обработчики событий в проектах Office. For information about creating event handlers, see How to: Create event handlers in Office projects.
Создайте метод с именем WriteStringToCell , который записывает текст в именованный диапазон. Create a method called WriteStringToCell that writes text to a named range. Этот метод вызывается из формы, и ввод пользователя передается в элемент управления NamedRange , formInput , в ячейку A1. This method is called from the form, and the user’s input is passed to the NamedRange control, formInput , on cell A1.
Далее добавьте в форму код для обработки события нажатия кнопки. Next, add code to the form to handle the button’s click event.
Отправка сведений на лист Send information to the worksheet
Отправка информации в лист To send information to the worksheet
Щелкните правой кнопкой мыши В GetInputString в обозревателе решений и выберите Конструктор представлений. Right-click GetInputString in Solution Explorer, and then click View Designer.
Дважды щелкните кнопку, чтобы открыть файл кода с добавленным обработчиком событий Click кнопки. Double-click the button to open the code file with the button’s Click event handler added.
Добавьте код в обработчик событий для приема входных данных из текстового поля, передачи их в функцию WriteStringToCell , а затем закрытия формы. Add code to the event handler to take the input from the text box, send it to the function WriteStringToCell , and then close the form.
Тест Test
Теперь можно запустить проект. You can now run the project. Появляется форма Windows Forms, и введенные данные отображаются в листе. The Windows Form appears, and your input appears in the worksheet.
Проверка книги To test your workbook
Нажмите клавишу F5 , чтобы запустить проект. Press F5 to run your project.
Убедитесь, что форма Windows Forms появилась. Confirm that the Windows Form appears.
Введите Hello World в текстовом поле и нажмите кнопку ОК. Type Hello World in the text box, and then click OK.
Убедитесь, что сообщение Hello World появилось в ячейке A1 листа. Confirm that Hello World appears in cell A1 of the worksheet.
Дальнейшие действия Next steps
В этом пошаговом руководстве описываются основные принципы отображения формы Windows Forms и передачи данных в лист. This walkthrough shows the basics of showing a Windows Form and passing data to a worksheet. Вам может потребоваться выполнить другие задачи, приведенные ниже. Other tasks you may want to perform include:
Использование элементов управления Windows Forms в книге Excel или документе Word. Use Windows Forms controls on an Excel workbook or a Word document. Дополнительные сведения см. в разделе Windows Forms элементы управления в документах Office. For more information, see Windows Forms controls on Office documents overview.
Изменение пользовательского интерфейса Microsoft Office приложения из настройки на уровне документа или надстройки VSTO. Modify the user interface of a Microsoft Office application from a document-level customization or a VSTO Add-in. Дополнительные сведения см. в разделе Настройка пользовательского интерфейса Office. For more information, see Office UI customization.