- Всплывающее окно в winform С#
- Диалоговые окна в Windows Forms Dialog Boxes in Windows Forms
- в этом разделе In This Section
- Связанные разделы Related Sections
- Popup window in winform c#
- 6 Answers 6
- Winform : How to create a new popup window using C#
- Line by line code explanation
- Context Menu. Popup Событие
- Определение
- Тип события
- Примеры
- Комментарии
Всплывающее окно в winform С#
Я работаю над проектом, где мне нужно всплывающее окно. Но дело в том, что я также хочу иметь возможность добавлять текстовые поля и т.д. В это всплывающее окно через конструктор форм.
Итак, в основном у меня есть кнопка, и когда вы нажимаете на нее, она откроет другое окно, которое я разработал в дизайнере форм.
Я занимаюсь поиском в Интернете, но не нашел того, что мне было нужно, поэтому я надеялся, что вы, ребята, сможете мне помочь!
Просто создайте другую форму (давайте назовем ее FormPopoup ) с помощью Visual studio. В обработчике кнопок напишите код followng:
Если вам нужно использовать немодальное окно: form.Show(); . Если вам нужен диалог (так что ваш код будет зависать в этом вызове до закрытия открытой формы), используйте: form.ShowDialog()
Формы в С# – это классы, наследующие базовый класс Form .
Вы можете показать всплывающее окно, создав экземпляр класса и вызвав ShowDialog() .
Это не так просто, потому что всплывающие окна не поддерживаются в формах Windows. Хотя формы окон основаны на win32 и в win32 всплывающие окна поддерживаются.
Если вы примете несколько трюков, следующий код заставит вас всплывать. Вы решаете, хотите ли вы использовать его хорошо:
Поэкспериментируйте с ним немного, вам нужно поиграть со своим положением и его размером. Используйте его неправильно, и ничего не отображается.
Если вы хотите создать новую форму при нажатии кнопки, код ниже может вам пригодиться:
Здесь вы также можете использовать метод “Показать диалог”
“Но дело в том, что я также хочу иметь возможность добавлять текстовые поля и т.д. в это всплывающее окно через конструктор форм”.
Это неясно из вашего описания на каком этапе процесса разработки вы находитесь. Если вы еще не поняли это, чтобы создать новую форму, нажмите Проект → Добавить Windows Form, затем введите имя для формы и нажмите кнопку “Добавить”. Теперь вы можете добавить элементы управления в свою форму, как и следовало ожидать.
Когда придет время для его отображения, следуйте советам других сообщений, чтобы создать экземпляр, и вызовите Show() или ShowDialog(), если это необходимо.
Я использую этот метод.
добавить из того, что вы хотите всплывать, добавить все элементы управления, которые вам нужны.
в коде вы можете обрабатывать ввод пользователя и возвращать результат вызывающему абоненту.
для всплывающей формы просто создайте новый экземпляр формы и метода show.
Диалоговые окна в Windows Forms Dialog Boxes in Windows Forms
Диалоговые окна используются для взаимодействия с пользователем и получения информации. Dialog boxes are used to interact with the user and retrieve information. Проще говоря, диалоговое окно представляет собой форму со значением ее свойства перечисления FormBorderStyle, установленным в FixedDialog . In simple terms, a dialog box is a form with its FormBorderStyle enumeration property set to FixedDialog . Пользовательские диалоговые окна можно создавать с помощью конструктор Windows Forms в Visual Studio. You can construct your own custom dialog boxes by using the Windows Forms Designer in Visual Studio. Для настройки диалоговых окон под конкретные потребности можно добавить элементы управления, такие как Label , Textbox и Button . Add controls such as Label , Textbox , and Button to customize dialog boxes to your specific needs. .NET Framework также содержит предопределенные диалоговые окна, такие как Открытие файлов и окна сообщений, которые можно адаптировать для собственных приложений. The .NET Framework also includes predefined dialog boxes, such as File Open and message boxes, which you can adapt for your own applications. Дополнительные сведения см. в разделе элементы управления и компоненты диалоговых окон. For more information, see Dialog-Box Controls and Components.
в этом разделе In This Section
Связанные разделы Related Sections
Элементы управления и компоненты диалоговых окон Dialog-Box Controls and Components
Список стандартных элементов управления диалоговых окон. Lists the predefined dialog box controls.
Изменение внешнего вида Windows Forms Changing the Appearance of Windows Forms
Содержит ссылки на разделы, описывающие, как изменить внешний вид приложений Windows Forms. Contains links to topics that describe how to change the appearance of Windows Forms applications.
Общие сведения об элементе управления TabControl TabControl Control Overview
Объясняется, как включить элемент управления «Вкладка» в диалоговое окно. Explains how you incorporate the tab control into a dialog box.
Popup window in winform c#
I’m working on a project where I need a popup window. But the thing is I also want to be able to add textboxes etc in this popup window thru the form designer.
So basically I have a button and when you click on it it will open another window that I’ve designed in the form designer.
I’ve been doing some googling but I haven’t found what I needed yet so I was hoping you guys could help me!
6 Answers 6
Just create another form (let’s call it formPopup ) using Visual Studio. In a button handler write the following code:
If you need a non-modal window use: formPopup.Show(); . If you need a dialog (so your code will hang on this invocation until you close the opened form) use: formPopup.ShowDialog()
This is not so easy because basically popups are not supported in windows forms. Although windows forms is based on win32 and in win32 popup are supported. If you accept a few tricks, following code will set you going with a popup. You decide if you want to put it to good use :
Experiment with it a bit, you have to play around with its position and its size. Use it wrong and nothing shows.
Forms in C# are classes that inherit the Form base class.
You can show a popup by creating an instance of the class and calling ShowDialog() .
If you mean to create a new form when a button is clicked, the below code may be of some use to you:
From here, you could also use the ‘Show Dialog’ method
«But the thing is I also want to be able to add textboxes etc in this popup window thru the form designer.»
It’s unclear from your description at what stage in the development process you’re in. If you haven’t already figured it out, to create a new Form you click on Project —> Add Windows Form, then type in a name for the form and hit the «Add» button. Now you can add controls to your form as you’d expect.
When it comes time to display it, follow the advice of the other posts to create an instance and call Show() or ShowDialog() as appropriate.
Winform : How to create a new popup window using C#
When I started to learn WinForm programming, one thing that I wondered was how to create additional window forms on already existing Winform Project. For example I wanted to create a popup window for editing purposes. I knew what code to write that would instantiate a new form but didn’t know how to edit that form in the designer.
In this article we are going to create a Winform Project from scratch that will contain main form and also one additional regular form which will act as a popup dialog window with OK / Cancel buttons. This popup dialog box will be shown when button on the main form is clicked. When the popup window closes, the main form will check which button (either OK or Cancel) was clicked.
Finished project will look something like this:
So lets start. Follow these steps:
- Start the Visual Studio and create a new WinForms project. If you are unsure how to do that or you have trouble finding the WinForms Template, check the How to create WinForms project using Visual Studio article for more detail.
- Drag a Button Control from a ToolBox (View > Toolbox).
Click image to enlarge
- In Text property type OK
- In DialogResult property the dropdown menu will be shown. Choose OK as shown in the image above.
Line by line code explanation
Now Let’s examine the above code more closely by focusing on highlighted lines 3, 4, 5 and 13:
Here we are instantiating the PopupForm class. This class was created in steps 3 and 4 when we selected Add > Window Form and named it PopupForm .
For this code you need to be aware of the following things:
- ShowDialog method will open the form as a modal dialog box. This basically means that the user will not be able to interact with the main form until the PopupForm is closed.
- Another feature of the modal forms is that the code after ShowDialog method will not get executed, you guessed it, until the popup form is closed.
Type of variable dialogresult is DialogResult Enumeration, so we compare that variable against the possible values of that enumeration.
When we do not need the popup form anymore, we dispose of it by calling Dispose method. Reason for calling Dispose method is that when you click either OK or Close button (X button), the popup form will only get hidden and not closed. Without Dispose() we would create additional instances with every button click on the main form.
I hope you found this article useful. If you still have questions, drop me a comment and I might include your problem with the solution in any future update.
Context Menu. Popup Событие
Определение
Происходит перед отображением контекстного меню. Occurs before the shortcut menu is displayed.
Тип события
Примеры
В следующем примере кода создается обработчик событий для Popup события ContextMenu . The following code example creates an event handler for the Popup event of the ContextMenu. Код в обработчике событий определяет, какой из двух элементов управления PictureBox с именем pictureBox1 и TextBox именем textBox1 является элементом управления, отображающим контекстное меню. The code in the event handler determines which of two controls a PictureBox named pictureBox1 and a TextBox named textBox1 is the control displaying the shortcut menu. В зависимости от того, какой элемент управления привел ContextMenu к отображению контекстного меню, элемент управления добавляет соответствующие MenuItem объекты в ContextMenu . Depending on which control caused the ContextMenu to display its shortcut menu, the control adds the appropriate MenuItem objects to the ContextMenu. В этом примере предполагается, что у вас есть экземпляр ContextMenu класса с именем contextMenu1 , определенный в форме. This example requires that you have an instance of the ContextMenu class, named contextMenu1 , defined within the form. В этом примере также требуется, чтобы в TextBox форму можно было PictureBox Добавить и, а ContextMenu свойству этих элементов управления присвоено значение contextMenu1 . This example also requires that you have a TextBox and PictureBox added to a form and that the ContextMenu property of these controls is set to contextMenu1 .
Комментарии
Это событие можно использовать для инициализации MenuItem объектов перед их отображением. You can use this event to initialize the MenuItem objects before they are displayed. Например, если вы используете ContextMenu для трех TextBox элементов управления и хотите отключить определенные пункты меню в в ContextMenu зависимости от того TextBox , что отображает контекстное меню, можно создать обработчик событий для этого события. For example, if you use a ContextMenu for three TextBox controls and you want to disable certain menu items in the ContextMenu depending on which TextBox is displaying the shortcut menu, you can create an event handler for this event. Можно использовать свойство, SourceControl чтобы определить, что TextBox собирается отображать ContextMenu и отключить соответствующие MenuItem объекты. You could use the SourceControl property to determine which TextBox is about to display the ContextMenu and disable the appropriate MenuItem objects.
Дополнительные сведения об обработке событий см. в разделе обработка и вызов событий. For more information about handling events, see Handling and Raising Events.