- Form. Show(IWin32Window) Метод
- Определение
- Параметры
- Исключения
- Комментарии
- Form. Shown Событие
- Определение
- Тип события
- Примеры
- Комментарии
- Как добавить форму в проект (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
- Form2.show()
Form. Show(IWin32Window) Метод
Определение
Показывает форму с указанным владельцем. Shows the form with the specified owner to the user.
Параметры
Любой объект, который реализует IWin32Window, представляющий окно верхнего уровня, которое станет владельцем этой формы. Any object that implements IWin32Window and represents the top-level window that will own this form.
Исключения
Отображаемая форма уже отображена. The form being shown is already visible.
-или- -or- Форма, указанная в параметре owner , совпадает с отображаемой формой. The form specified in the owner parameter is the same as the form being shown.
-или- -or- Отображаемая форма отключена. The form being shown is disabled.
-или- -or- Отображаемая форма не является окном верхнего уровня. The form being shown is not a top-level window.
-или- -or- Отображаемая в виде диалогового окна форма уже является модальной формой. The form being shown as a dialog box is already a modal form.
-или- -or- Текущий процесс не выполняется в интерактивном пользовательском режиме (дополнительные сведения см. в описании свойства UserInteractive). The current process is not running in user interactive mode (for more information, see UserInteractive).
Комментарии
Этот метод можно использовать для вывода не модальной формы. You can use this method to display a non-modal form. При использовании этого метода Owner свойство формы устанавливается в значение owner . When you use this method, the Owner property of the form is set to owner . Немодальная форма может использовать Owner свойство для получения сведений о форме-владельце. The non-modal form can use the Owner property to get information about the owning form. Вызов этого метода идентичен заданию Owner Свойства немодального объекта и последующему вызову Show() метода. Calling this method is identical to setting the Owner property of the non-modal and then calling the Show() method.
Отображение формы эквивалентно присвоению Visible свойству значения true . Showing the form is equivalent to setting the Visible property to true . После Show вызова метода Visible свойство возвращает значение true до тех пор, пока Hide не будет вызван метод. After the Show method is called, the Visible property returns a value of true until the Hide method is called.
Form. Shown Событие
Определение
Происходит при первом отображении формы. Occurs whenever the form is first displayed.
Тип события
Примеры
В следующем примере демонстрируется использование этого элемента. The following example demonstrates the use of this member. В этом примере обработчик событий сообщает о возникновении Shown события. In the example, an event handler reports on the occurrence of the Shown event. Этот отчет поможет вам узнать, когда происходит событие и может помочь при отладке. This report helps you to learn when the event occurs and can assist you in debugging. Чтобы сообщить о нескольких событиях или о событиях, которые происходят часто, рассмотрите возможность замены MessageBox.Show Console.WriteLine или добавления сообщения в многострочный TextBox . To report on multiple events or on events that occur frequently, consider replacing MessageBox.Show with Console.WriteLine or appending the message to a multiline TextBox.
Чтобы выполнить пример кода, вставьте его в проект, содержащий экземпляр типа Form с именем Form1 . To run the example code, paste it into a project that contains an instance of type Form named Form1 . Затем убедитесь, что обработчик событий связан с Shown событием. Then ensure that the event handler is associated with the Shown event.
Комментарии
ShownСобытие вызывается только при первом отображении формы; последующее свертывание, увеличение, восстановление, скрытие, отображение или невозможность, а также перерисовку не вызовет этого события. The Shown event is only raised the first time a form is displayed; subsequently minimizing, maximizing, restoring, hiding, showing, or invalidating and repainting will not raise this event. Дополнительные сведения о порядке событий формы см. в разделе Порядок событий в Windows Forms. For more information about the order of events of a form, see Order of Events in Windows Forms.
Дополнительные сведения об обработке событий см. в разделе обработка и вызов событий. For more information about handling events, see Handling and Raising Events.
Как добавить форму в проект (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:
Form2.show()
Show() и showdialog()
У меня созданы 2 формы. При нажатии на кнопку на первой форме открывается вторая (методом Show()) и.
MessageBox.Show()
Здравствуйте! Я вызываю метод MessageBox.Show(«. «) и мне необходимо, что бы пока я его не.
Из Form2 в Form1
В form1, после нажатия на кнопку открывается form2. Там можно выбрать и просмотреть картинки. Так.
form2 главная
Как можно сделать form2 главной?
Form FormName = new Form2();
FormName.Show();
Тематические курсы и обучение профессиям онлайн Профессия С#-разработчик (Skillbox) Архитектор ПО (Skillbox) Профессия Тестировщик (Skillbox) |
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.
Из form1 в form2
Запарился уже искать то что нужно! В общем при нажатии на форм 1 считываются координаты и в.
Form.Show() в потоке
Необходимо вызвать метод Show в потоке. Когда форма появляется на экране она зависает пока цикл не.
Не выходит MessageBox.Show
Приветствую, перепробовал множество вариантов но при нажатие на кнопку так и не выходит. Не понимаю.
Создание Form2 и её контролов
Здравствуйте! Решил поэкспериментировать и что-то получается не то! Итак есть from1, на которой.