|
Заблокирован |
||||
|
1 |
||||
|
29.10.2014, 15:48. Показов 12094. Ответов 3 Метки нет (Все метки)
Почему у меня «Ок» и в верху и в низу я в программе прописываю 1 раз «Ок»
Как мне можно сделать так что бы изменить текст который пишется сверху? Изображения
__________________
0 |
|
quwy Native x86 5175 / 3022 / 874 Регистрация: 13.02.2013 Сообщений: 9,635 |
||||
|
29.10.2014, 15:54 |
2 |
|||
|
Решение
Почему у меня «Ок» и в верху и в низу я в программе прописываю 1 раз «Ок» Неужели вы не видите, что в заголовке окна и на кнопке разный текст?
Как мне можно сделать так что бы изменить текст который пишется сверху? Если бы вы проявили хотя бы минимальное любопытство и хоть на один символ изменили строку чужого кода, то этот вопрос просто не возник бы. Что показывает этот код:
?
0 |
|
Заблокирован |
|
|
29.10.2014, 15:56 [ТС] |
3 |
|
quwy,
0 |
|
2 / 2 / 0 Регистрация: 25.09.2014 Сообщений: 71 |
|
|
29.10.2014, 16:09 |
4 |
|
MessageBox.Show («Текст сообщения», «Заголовок окна MessageBox»);
1 |
User-1488931086 posted
i want to change message box tile. title shows like «Message from webpage»
No,this is the system dialog so you CANNOT change the title of that;
But however,you can use this:
1)Model Pop-Up Dialog from Microsoft’s AJAX control:http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ModalPopup/ModalPopup.aspx
http://www.asp.net/ajaxlibrary/AjaxControlToolkitSampleSite/ConfirmButton/ConfirmButton.aspx
2)This Nice Message made from Microsoft Employee(Strongly Recommanded!Just plz use MessageTitle property to change the title……)
http://code.msdn.microsoft.com/CSASPNETMessageBox-3f1b547d
Sample from 2nd one
'****************************** Module Header ******************************
'Module Name: MessageBox.vb
'Project: VBASPNETIntelligentErrorPage
'Copyright (c) Microsoft Corporation.
'
'The sample code demonstrates how to create a MessageBox in asp.net, usually we
'often use JavaScript functions "alert()" or "confirm()" to show simple messages
'and make a simple choice with customers, but these dialog boxes is very simple,
'we can not add any different and complicate controls, images or styles. As we know,
'good web sites always have their own web styles, such as typeface and colors,
'and in this situation, JavaScript dialog boxes looks not very well. So this sample
'shows how to make an Asp.net MessageBox.
'
'The MessageBox class includes basic properties and events. The Show() method generates
'all html code by class properties.
'
'This source is subject to the Microsoft Public License.
'See http://www.microsoft.com/en-us/openness/resources/licenses.aspx#MPL
'All other rights reserved.
'
'THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
'EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
'WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
'***************************************************************************/
Public Class MessageBox
Public Property MessageText() As String
Get
Return m_MessageText
End Get
Set(ByVal value As String)
m_MessageText = value
End Set
End Property
Private m_MessageText As String
Public Property MessageTitle() As String
Get
Return m_MessageTitle
End Get
Set(ByVal value As String)
m_MessageTitle = value
End Set
End Property
Private m_MessageTitle As String
Public Property MessageIcons() As MessageBoxIcons
Get
Return m_MessageIcons
End Get
Set(ByVal value As MessageBoxIcons)
m_MessageIcons = value
End Set
End Property
Private m_MessageIcons As MessageBoxIcons
Public Property MessageButtons() As MessageBoxButtons
Get
Return m_MessageButtons
End Get
Set(ByVal value As MessageBoxButtons)
m_MessageButtons = value
End Set
End Property
Private m_MessageButtons As MessageBoxButtons
Public Property MessageStyles() As MessageBoxStyle
Get
Return m_MessageStyles
End Get
Set(ByVal value As MessageBoxStyle)
m_MessageStyles = value
End Set
End Property
Private m_MessageStyles As MessageBoxStyle
Public SuccessEvent As New List(Of String)()
Public FailedEvent As New List(Of String)()
''' <summary>
''' Define an Asp.net MessageBox instance.
''' </summary>
Public Sub New()
Me.MessageIcons = MessageBoxIcons.System
Me.MessageButtons = MessageBoxButtons.Ok
Me.MessageStyles = MessageBoxStyle.StyleA
End Sub
''' <summary>
''' Define an Asp.net MessageBox instance.
''' </summary>
''' <param name="text">Message Box text property.</param>
Public Sub New(ByVal text As String)
Me.MessageText = text
Me.MessageIcons = MessageBoxIcons.System
Me.MessageButtons = MessageBoxButtons.Ok
Me.MessageStyles = MessageBoxStyle.StyleA
End Sub
''' <summary>
''' Define an Asp.net MessageBox instance.
''' </summary>
''' <param name="text">MessageBox text property.</param>
''' <param name="title">MessageBox title property.</param>
Public Sub New(ByVal text As String, ByVal title As String)
Me.MessageText = text
Me.MessageTitle = title
Me.MessageIcons = MessageBoxIcons.System
Me.MessageButtons = MessageBoxButtons.Ok
Me.MessageStyles = MessageBoxStyle.StyleA
End Sub
''' <summary>
''' Define an Asp.net MessageBox instance.
''' </summary>
''' <param name="text">MessageBox text property.</param>
''' <param name="title">MessageBox title property.</param>
''' <param name="icons">MessageBox icon property.</param>
''' <param name="buttons">MessageBox button style.</param>
Public Sub New(ByVal text As String, ByVal title As String, ByVal icons As MessageBoxIcons, ByVal buttons As MessageBoxButtons, ByVal styles As MessageBoxStyle)
Me.MessageText = text
Me.MessageTitle = title
Me.MessageIcons = icons
Me.MessageButtons = buttons
Me.MessageStyles = styles
End Sub
Public Function Show(ByVal sender As Object) As String
Dim iconUrl As String = String.Empty
Dim buttonStyle As String = String.Empty
Dim buttonHTML As String = String.Empty
Dim scriptHTML As String = String.Empty
Dim coreHTML As String = String.Empty
Dim builder As New StringBuilder()
Select Case Me.MessageIcons
Case MessageBoxIcons.None
iconUrl = String.Empty
Exit Select
Case MessageBoxIcons.Warnning
iconUrl = "<img src ='../Images/1.jpg' />"
Exit Select
Case MessageBoxIcons.[Error]
iconUrl = "<img src ='../Images/2.jpg' />"
Exit Select
Case MessageBoxIcons.Question
iconUrl = "<img src ='../Images/3.jpg' />"
Exit Select
Case MessageBoxIcons.System
iconUrl = "<img src ='../Images/4.jpg' />"
Exit Select
End Select
Select Case Me.MessageStyles
Case MessageBoxStyle.StyleA
buttonStyle = "button_classA"
Exit Select
Case MessageBoxStyle.StyleB
buttonStyle = "button_classB"
Exit Select
End Select
Select Case Me.MessageButtons
Case MessageBoxButtons.Ok
buttonHTML = MessageBoxCore.MessageBoxButtonHtml
buttonHTML = [String].Format(buttonHTML, "OK", buttonStyle, "Yes();")
builder.Append(buttonHTML)
Exit Select
Case MessageBoxButtons.OKCancel
Dim buttonOKHTML As String = String.Empty
Dim buttonCancelHTML As String = String.Empty
buttonOKHTML = MessageBoxCore.MessageBoxButtonHtml
buttonOKHTML = [String].Format(buttonOKHTML, "OK", buttonStyle, "Yes();")
builder.Append(buttonOKHTML)
builder.Append(" ")
buttonCancelHTML = MessageBoxCore.MessageBoxButtonHtml
buttonCancelHTML = [String].Format(buttonCancelHTML, "Cancel", buttonStyle, "No();")
builder.Append(buttonCancelHTML)
Exit Select
Case MessageBoxButtons.YesOrNo
Dim buttonYesHTML As String = String.Empty
Dim buttonNoHTML As String = String.Empty
buttonYesHTML = MessageBoxCore.MessageBoxButtonHtml
buttonYesHTML = [String].Format(buttonYesHTML, "Yes", buttonStyle, "Yes();")
builder.Append(buttonYesHTML)
builder.Append(" ")
buttonNoHTML = MessageBoxCore.MessageBoxButtonHtml
buttonNoHTML = [String].Format(buttonNoHTML, "No", buttonStyle, "No();")
builder.Append(buttonNoHTML)
Exit Select
Case MessageBoxButtons.YesNoCancel
Dim buttonYesCHTML As String = String.Empty
Dim buttonNoCHTML As String = String.Empty
Dim buttonCancelCHTML As String = String.Empty
buttonYesCHTML = MessageBoxCore.MessageBoxButtonHtml
buttonYesCHTML = [String].Format(buttonYesCHTML, "Yes", buttonStyle, "Yes();")
builder.Append(buttonYesCHTML)
builder.Append(" ")
buttonNoCHTML = MessageBoxCore.MessageBoxButtonHtml
buttonNoCHTML = [String].Format(buttonNoCHTML, "No", buttonStyle, "No();")
builder.Append(buttonNoCHTML)
builder.Append(" ")
buttonCancelCHTML = MessageBoxCore.MessageBoxButtonHtml
buttonCancelCHTML = [String].Format(buttonCancelCHTML, "Cancel", buttonStyle, "No();")
builder.Append(buttonCancelCHTML)
Exit Select
End Select
Dim successName As String = String.Empty
Dim failedName As String = "1"
Dim successBuilder As New StringBuilder()
Dim failedBuilder As New StringBuilder()
If SuccessEvent IsNot Nothing AndAlso SuccessEvent.Count <> 0 Then
Dim eventCounts As Integer = SuccessEvent.Count
For i As Integer = 0 To eventCounts - 1
successBuilder.Append("PageMethods.")
successBuilder.Append(SuccessEvent(i).ToString())
successBuilder.Append("(null,null,Success, Failed);")
Next
successName = successBuilder.ToString()
End If
If FailedEvent IsNot Nothing AndAlso FailedEvent.Count <> 0 Then
Dim eventCounts As Integer = FailedEvent.Count
For i As Integer = 0 To eventCounts - 1
failedBuilder.Append("PageMethods.")
failedBuilder.Append(FailedEvent(i).ToString())
failedBuilder.Append("(null,null,Success, Failed);")
Next
failedName = failedBuilder.ToString()
End If
scriptHTML = MessageBoxCore.MessageBoxScript
scriptHTML = [String].Format(scriptHTML, successName, failedName)
coreHTML = MessageBoxCore.MessageBoxHTML
coreHTML = [String].Format(coreHTML, Me.MessageTitle, iconUrl, Me.MessageText, builder.ToString())
TryCast(sender, Page).ClientScript.RegisterClientScriptBlock(sender.[GetType](), "_arg", scriptHTML, True)
Return coreHTML
End Function
Public Enum MessageBoxButtons
Ok
OKCancel
YesOrNo
YesNoCancel
End Enum
Public Enum MessageBoxIcons
None
Warnning
Question
System
[Error]
End Enum
Public Enum MessageBoxStyle
StyleA
StyleB
End Enum
End Class
User-1488931086 posted
i want to change message box tile. title shows like «Message from webpage»
No,this is the system dialog so you CANNOT change the title of that;
But however,you can use this:
1)Model Pop-Up Dialog from Microsoft’s AJAX control:http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ModalPopup/ModalPopup.aspx
http://www.asp.net/ajaxlibrary/AjaxControlToolkitSampleSite/ConfirmButton/ConfirmButton.aspx
2)This Nice Message made from Microsoft Employee(Strongly Recommanded!Just plz use MessageTitle property to change the title……)
http://code.msdn.microsoft.com/CSASPNETMessageBox-3f1b547d
Sample from 2nd one
'****************************** Module Header ******************************
'Module Name: MessageBox.vb
'Project: VBASPNETIntelligentErrorPage
'Copyright (c) Microsoft Corporation.
'
'The sample code demonstrates how to create a MessageBox in asp.net, usually we
'often use JavaScript functions "alert()" or "confirm()" to show simple messages
'and make a simple choice with customers, but these dialog boxes is very simple,
'we can not add any different and complicate controls, images or styles. As we know,
'good web sites always have their own web styles, such as typeface and colors,
'and in this situation, JavaScript dialog boxes looks not very well. So this sample
'shows how to make an Asp.net MessageBox.
'
'The MessageBox class includes basic properties and events. The Show() method generates
'all html code by class properties.
'
'This source is subject to the Microsoft Public License.
'See http://www.microsoft.com/en-us/openness/resources/licenses.aspx#MPL
'All other rights reserved.
'
'THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
'EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
'WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
'***************************************************************************/
Public Class MessageBox
Public Property MessageText() As String
Get
Return m_MessageText
End Get
Set(ByVal value As String)
m_MessageText = value
End Set
End Property
Private m_MessageText As String
Public Property MessageTitle() As String
Get
Return m_MessageTitle
End Get
Set(ByVal value As String)
m_MessageTitle = value
End Set
End Property
Private m_MessageTitle As String
Public Property MessageIcons() As MessageBoxIcons
Get
Return m_MessageIcons
End Get
Set(ByVal value As MessageBoxIcons)
m_MessageIcons = value
End Set
End Property
Private m_MessageIcons As MessageBoxIcons
Public Property MessageButtons() As MessageBoxButtons
Get
Return m_MessageButtons
End Get
Set(ByVal value As MessageBoxButtons)
m_MessageButtons = value
End Set
End Property
Private m_MessageButtons As MessageBoxButtons
Public Property MessageStyles() As MessageBoxStyle
Get
Return m_MessageStyles
End Get
Set(ByVal value As MessageBoxStyle)
m_MessageStyles = value
End Set
End Property
Private m_MessageStyles As MessageBoxStyle
Public SuccessEvent As New List(Of String)()
Public FailedEvent As New List(Of String)()
''' <summary>
''' Define an Asp.net MessageBox instance.
''' </summary>
Public Sub New()
Me.MessageIcons = MessageBoxIcons.System
Me.MessageButtons = MessageBoxButtons.Ok
Me.MessageStyles = MessageBoxStyle.StyleA
End Sub
''' <summary>
''' Define an Asp.net MessageBox instance.
''' </summary>
''' <param name="text">Message Box text property.</param>
Public Sub New(ByVal text As String)
Me.MessageText = text
Me.MessageIcons = MessageBoxIcons.System
Me.MessageButtons = MessageBoxButtons.Ok
Me.MessageStyles = MessageBoxStyle.StyleA
End Sub
''' <summary>
''' Define an Asp.net MessageBox instance.
''' </summary>
''' <param name="text">MessageBox text property.</param>
''' <param name="title">MessageBox title property.</param>
Public Sub New(ByVal text As String, ByVal title As String)
Me.MessageText = text
Me.MessageTitle = title
Me.MessageIcons = MessageBoxIcons.System
Me.MessageButtons = MessageBoxButtons.Ok
Me.MessageStyles = MessageBoxStyle.StyleA
End Sub
''' <summary>
''' Define an Asp.net MessageBox instance.
''' </summary>
''' <param name="text">MessageBox text property.</param>
''' <param name="title">MessageBox title property.</param>
''' <param name="icons">MessageBox icon property.</param>
''' <param name="buttons">MessageBox button style.</param>
Public Sub New(ByVal text As String, ByVal title As String, ByVal icons As MessageBoxIcons, ByVal buttons As MessageBoxButtons, ByVal styles As MessageBoxStyle)
Me.MessageText = text
Me.MessageTitle = title
Me.MessageIcons = icons
Me.MessageButtons = buttons
Me.MessageStyles = styles
End Sub
Public Function Show(ByVal sender As Object) As String
Dim iconUrl As String = String.Empty
Dim buttonStyle As String = String.Empty
Dim buttonHTML As String = String.Empty
Dim scriptHTML As String = String.Empty
Dim coreHTML As String = String.Empty
Dim builder As New StringBuilder()
Select Case Me.MessageIcons
Case MessageBoxIcons.None
iconUrl = String.Empty
Exit Select
Case MessageBoxIcons.Warnning
iconUrl = "<img src ='../Images/1.jpg' />"
Exit Select
Case MessageBoxIcons.[Error]
iconUrl = "<img src ='../Images/2.jpg' />"
Exit Select
Case MessageBoxIcons.Question
iconUrl = "<img src ='../Images/3.jpg' />"
Exit Select
Case MessageBoxIcons.System
iconUrl = "<img src ='../Images/4.jpg' />"
Exit Select
End Select
Select Case Me.MessageStyles
Case MessageBoxStyle.StyleA
buttonStyle = "button_classA"
Exit Select
Case MessageBoxStyle.StyleB
buttonStyle = "button_classB"
Exit Select
End Select
Select Case Me.MessageButtons
Case MessageBoxButtons.Ok
buttonHTML = MessageBoxCore.MessageBoxButtonHtml
buttonHTML = [String].Format(buttonHTML, "OK", buttonStyle, "Yes();")
builder.Append(buttonHTML)
Exit Select
Case MessageBoxButtons.OKCancel
Dim buttonOKHTML As String = String.Empty
Dim buttonCancelHTML As String = String.Empty
buttonOKHTML = MessageBoxCore.MessageBoxButtonHtml
buttonOKHTML = [String].Format(buttonOKHTML, "OK", buttonStyle, "Yes();")
builder.Append(buttonOKHTML)
builder.Append(" ")
buttonCancelHTML = MessageBoxCore.MessageBoxButtonHtml
buttonCancelHTML = [String].Format(buttonCancelHTML, "Cancel", buttonStyle, "No();")
builder.Append(buttonCancelHTML)
Exit Select
Case MessageBoxButtons.YesOrNo
Dim buttonYesHTML As String = String.Empty
Dim buttonNoHTML As String = String.Empty
buttonYesHTML = MessageBoxCore.MessageBoxButtonHtml
buttonYesHTML = [String].Format(buttonYesHTML, "Yes", buttonStyle, "Yes();")
builder.Append(buttonYesHTML)
builder.Append(" ")
buttonNoHTML = MessageBoxCore.MessageBoxButtonHtml
buttonNoHTML = [String].Format(buttonNoHTML, "No", buttonStyle, "No();")
builder.Append(buttonNoHTML)
Exit Select
Case MessageBoxButtons.YesNoCancel
Dim buttonYesCHTML As String = String.Empty
Dim buttonNoCHTML As String = String.Empty
Dim buttonCancelCHTML As String = String.Empty
buttonYesCHTML = MessageBoxCore.MessageBoxButtonHtml
buttonYesCHTML = [String].Format(buttonYesCHTML, "Yes", buttonStyle, "Yes();")
builder.Append(buttonYesCHTML)
builder.Append(" ")
buttonNoCHTML = MessageBoxCore.MessageBoxButtonHtml
buttonNoCHTML = [String].Format(buttonNoCHTML, "No", buttonStyle, "No();")
builder.Append(buttonNoCHTML)
builder.Append(" ")
buttonCancelCHTML = MessageBoxCore.MessageBoxButtonHtml
buttonCancelCHTML = [String].Format(buttonCancelCHTML, "Cancel", buttonStyle, "No();")
builder.Append(buttonCancelCHTML)
Exit Select
End Select
Dim successName As String = String.Empty
Dim failedName As String = "1"
Dim successBuilder As New StringBuilder()
Dim failedBuilder As New StringBuilder()
If SuccessEvent IsNot Nothing AndAlso SuccessEvent.Count <> 0 Then
Dim eventCounts As Integer = SuccessEvent.Count
For i As Integer = 0 To eventCounts - 1
successBuilder.Append("PageMethods.")
successBuilder.Append(SuccessEvent(i).ToString())
successBuilder.Append("(null,null,Success, Failed);")
Next
successName = successBuilder.ToString()
End If
If FailedEvent IsNot Nothing AndAlso FailedEvent.Count <> 0 Then
Dim eventCounts As Integer = FailedEvent.Count
For i As Integer = 0 To eventCounts - 1
failedBuilder.Append("PageMethods.")
failedBuilder.Append(FailedEvent(i).ToString())
failedBuilder.Append("(null,null,Success, Failed);")
Next
failedName = failedBuilder.ToString()
End If
scriptHTML = MessageBoxCore.MessageBoxScript
scriptHTML = [String].Format(scriptHTML, successName, failedName)
coreHTML = MessageBoxCore.MessageBoxHTML
coreHTML = [String].Format(coreHTML, Me.MessageTitle, iconUrl, Me.MessageText, builder.ToString())
TryCast(sender, Page).ClientScript.RegisterClientScriptBlock(sender.[GetType](), "_arg", scriptHTML, True)
Return coreHTML
End Function
Public Enum MessageBoxButtons
Ok
OKCancel
YesOrNo
YesNoCancel
End Enum
Public Enum MessageBoxIcons
None
Warnning
Question
System
[Error]
End Enum
Public Enum MessageBoxStyle
StyleA
StyleB
End Enum
End Class
Диалоговые окна:
WPF предлагает на выбор несколько видов диалоговых окон для приложений, но самым простым является MessageBox. Единственной его целью является отображение сообщений пользователю, и один/несколько вариантов выбора.
Использование MessageBox осуществляется с помощью вызова статического метода Show(), который может принимать на входе несколько различных параметров, необходимых для реализации запланированного Вами поведения. Мы рассмотрим некоторые варианты перегрузок данного метода, которые будут подкреплены кодом MessageBox.Show() и скриншотами. В конце главы Вы найдете полный код примера, который позволит Вам протестировать различные варианты использования MessageBox.
В своей самой простой форме, MessageBox принимает один параметр (сообщение для отображения пользователю):
MessageBox.Show("Hello, world!");
MessageBox с заголовком
Предыдущий пример не является особо полезным. Ситуацию может улучшить заголовок диалогового окна. К счастью, второй возможный параметр метода Show() позволяет определить заголовок:
MessageBox.Show("Hello, world!", "My App");
MessageBox с дополнительными кнопками
По умолчанию MessageBox имеет только одну «Ok» кнопку, но это можно легко изменить, если Вы вдруг захотите дать пользователю возможность ответа, а не просто показать какую-либо информацию. Также, обратите внимание, как с помощью n осуществляется поддержка многострочных сообщений в MessageBox:
MessageBox.Show("This MessageBox has extra options.nnHello, world?", "My App", MessageBoxButton.YesNoCancel);
Тем, какие кнопки отображать, Вы управляете, используя значение из перечисления MessageBoxButton. В него входят кнопки Yes, No и Cancel. Данные значения могут использоваться в следующих комбинациях:
- OK
- OKCancel
- YesNoCancel
- YesNo
Теперь Вам необходимо обработать варианты выбора пользователя. К счастью, метод MessageBox.Show() возвращает значение из перечисления MessageBoxResult. Вот пример:
MessageBoxResult result = MessageBox.Show("Would you like to greet the world with a "Hello, world"?", "My App", MessageBoxButton.YesNoCancel);
switch(result)
{
case MessageBoxResult.Yes:
MessageBox.Show("Hello to you too!", "My App");
break;
case MessageBoxResult.No:
MessageBox.Show("Oh well, too bad!", "My App");
break;
case MessageBoxResult.Cancel:
MessageBox.Show("Nevermind then...", "My App");
break;
}
Проверяя значение-результат метода MessageBox.Show(), становится возможной обработка пользовательского выбора, как видно из скриншотов.
MessageBox с иконкой
С помощью четвертого параметра, MessageBox может отображать иконки «по умолчанию» слева от текста сообщения:
MessageBox.Show("Hello, world!", "My App", MessageBoxButton.OK, MessageBoxImage.Information);
С использованием перечисления MessageBoxImage Вы можете выбирать между несколькими иконками, подходящими под определенную ситуацию. Вот полный список:
- Asterisk (звезда)
- Error (ошибка)
- Exclamation (восклицательный знак)
- Hand (рука)
- Information (информация)
- None (без иконки)
- Question (знак вопроса)
- Stop (стоп)
- Warning (внимание)
В основном названия этих иконок соответствуют содержанию, но Вы с легкостью можете поэкспериментировать с помощью статьи на MSDN, в которой проиллюстрировано использование всех иконок:
http://msdn.microsoft.com/en-us/library/system.windows.messageboximage.aspx
MessageBox с выбором по умолчанию
MessageBox выберет кнопку по умолчанию, при нажатии на Enter. Например, если вы отображаете диалоговое окно с кнопками «Yes» и «No», первая будет определена как выбор по умолчанию. Вы можете изменить это поведение, используя пятый параметр метода MessageBox.Show():
MessageBox.Show("Hello, world?", "My App", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);
Обратите внимание как на скриншоте приподнята кнопка «No» (выделена как выбранная).
Она сработает при нажатии на Enter или Space.
Полный пример
Как было обещано в начале главы, вот полный пример:
<Window x:Class="WpfTutorialSamples.Dialogs.MessageBoxSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MessageBoxSample" Height="250" Width="300">
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<StackPanel.Resources>
<Style TargetType="Button">
<Setter Property="Margin" Value="0,0,0,10" />
</Style>
</StackPanel.Resources>
<Button Name="btnSimpleMessageBox" Click="btnSimpleMessageBox_Click">Simple MessageBox</Button>
<Button Name="btnMessageBoxWithTitle" Click="btnMessageBoxWithTitle_Click">MessageBox with title</Button>
<Button Name="btnMessageBoxWithButtons" Click="btnMessageBoxWithButtons_Click">MessageBox with buttons</Button>
<Button Name="btnMessageBoxWithResponse" Click="btnMessageBoxWithResponse_Click">MessageBox with response</Button>
<Button Name="btnMessageBoxWithIcon" Click="btnMessageBoxWithIcon_Click">MessageBox with icon</Button>
<Button Name="btnMessageBoxWithDefaultChoice" Click="btnMessageBoxWithDefaultChoice_Click">MessageBox with default choice</Button>
</StackPanel>
</Window>
using System;
using System.Windows;
namespace WpfTutorialSamples.Dialogs
{
public partial class MessageBoxSample : Window
{
public MessageBoxSample()
{
InitializeComponent();
}
private void btnSimpleMessageBox_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello, world!");
}
private void btnMessageBoxWithTitle_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello, world!", "My App");
}
private void btnMessageBoxWithButtons_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("This MessageBox has extra options.nnHello, world?", "My App", MessageBoxButton.YesNoCancel);
}
private void btnMessageBoxWithResponse_Click(object sender, RoutedEventArgs e)
{
MessageBoxResult result = MessageBox.Show("Would you like to greet the world with a "Hello, world"?", "My App", MessageBoxButton.YesNoCancel);
switch(result)
{
case MessageBoxResult.Yes:
MessageBox.Show("Hello to you too!", "My App");
break;
case MessageBoxResult.No:
MessageBox.Show("Oh well, too bad!", "My App");
break;
case MessageBoxResult.Cancel:
MessageBox.Show("Nevermind then...", "My App");
break;
}
}
private void btnMessageBoxWithIcon_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello, world!", "My App", MessageBoxButton.OK, MessageBoxImage.Information);
}
private void btnMessageBoxWithDefaultChoice_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello, world?", "My App", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);
}
}
}
This article has been fully translated into the following languages:
-
Chinese
-
Czech
-
Danish
-
French
-
German
-
Hungarian
-
Italian
-
Japanese
-
Korean
-
Polish
-
Portuguese
-
Russian
-
Slovak
-
Spanish
-
Ukrainian
-
Vietnamese
Is your preferred language not on the list? Click here to help us translate this article into your language!
Последнее обновление: 31.10.2015
Как правило, для вывода сообщений применяется элемент MessageBox. Однако кроме сообственно вывода строки сообщения данный элемент может устанавливать
ряд настроек, которые определяют его поведение.
Для вывода сообщения в классе MessageBox предусмотрен метод Show, который имеет различные версии и может принимать ряд параметров.
Рассмотрим одну из наиболее используемых версий:
public static DialogResult Show( string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options )
Здесь применяются следующие параметры:
text: текст сообщения
caption: текст заголовка окна сообщения
buttons: кнопки, используемые в окне сообщения.
Принимает одно из значений перечисления MessageBoxButtons:
-
AbortRetryIgnore: три кнопки Abort (Отмена), Retry (Повтор), Ignore (Пропустить) -
OK: одна кнопка OK -
OKCancel: две кнопки OK и Cancel (Отмена) -
RetryCancel: две кнопки Retry (Повтор) и Cancel (Отмена) -
YesNo: две кнопки Yes и No -
YesNoCancel: три кнопки Yes, No и Cancel (Отмена)
Таким образом, в зависимости от выбора окно сообщения может иметь от одной до трех кнопок.
icon: значок окна сообщения. Может принимать одно из следующих значений перечисления MessageBoxIcon:
-
Asterisk, Information: значок, состоящий из буквы i в нижнем регистре, помещенной в кружок -
Error, Hand, Stop: значок, состоящий из белого знака «X» на круге красного цвета. -
Exclamation, Warning: значок, состоящий из восклицательного знака в желтом треугольнике -
Question: значок, состоящий из вопросительного знака на периметре круга -
None: значок у сообщения отсутствует
defaultButton: кнопка, на которую по умолчанию устанавливается фокус. Принимает одно из значений перечисления MessageBoxDefaultButton:
-
Button1: первая кнопка из тех, которые задаются перечислением MessageBoxButtons -
Button2: вторая кнопка -
Button3: третья кнопка
options: параметры окна сообщения. Принимает одно из значений перечисления MessageBoxOptions:
-
DefaultDesktopOnly: окно сообщения отображается на активном рабочем столе. -
RightAlign: текст окна сообщения выравнивается по правому краю -
RtlReading: все элементы окна располагаются в обратном порядке справа налево -
ServiceNotification: окно сообщения отображается на активном рабочем столе, даже если в системе не зарегистрирован ни один пользователь
Нередко используется один параметр — текст сообщения. Но посмотрим, как использовать остальные параметры. Пусть у нас есть кнопка, в обработчике
нажатия которой открывается следующее окно сообщения:
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(
"Выберите один из вариантов",
"Сообщение",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information,
MessageBoxDefaultButton.Button1,
MessageBoxOptions.DefaultDesktopOnly);
}
Однако нам не просто дается возможность установки кнопок в окне сообщения. Метод MessageBox.Show возвращает объект
DialogResult, с помощью которого мы можем узнать, какую кнопку в окне сообщения нажал пользователь. DialogResult представляет
перечисление, в котором определены следующие значения:
-
Abort: нажата кнопка Abort -
Retry: нажата кнопка Retry -
Ignore: нажата кнопка Ignore -
OK: нажата кнопка OK -
Cancel: нажата кнопка Cancel -
None: отсутствие результата -
Yes: нажата кнопка Yes и No -
No: нажата кнопка No
Используем обработку выбора пользователя, изменив обработчик нажатия кнопки следующим образом:
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show(
"Окрасить кнопку в красный цвет?",
"Сообщение",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information,
MessageBoxDefaultButton.Button1,
MessageBoxOptions.DefaultDesktopOnly);
if (result == DialogResult.Yes)
button1.BackColor=Color.Red;
this.TopMost = true;
}
И теперь, если в окне сообщения мы выберем выриант Yes, то кнопка окрасится в красный цвет.
C# MessageBox in Windows Forms displays a message with the given text and action buttons. You can also use MessageBox control to add additional options such as a caption, an icon, or help buttons. In this article, you’ll learn how to display and use a MessageBox in C# WinForms app. You will also learn how to use C# MessageBox class dynamically in code samples.
C# MessageBox
MessageBox class has an overloaded static Show method that displays a message box with a message and action buttons. The action buttons can be OK and Cancel, Yes and No etc. Here are some of the options that can be used in C# message box.
Simple MessageBox
The simplest form of a MessageBox is a dialog with a text and OK button. When you click OK button, the box disappears.
The following code snippet creates a simple Message Box.
- string message = «Simple MessageBox»;
- MessageBox.Show(message);
MessageBox with Title
The following code snippet creates a simple MessageBox with a title.
- string message = «Simple MessageBox»;
- string title = «Title»;
- MessageBox.Show(message, title);
MessageBox with Buttons
A MessageBox can have different button combinations such as YesNo and OKCancel. The MessageBoxButtons enumeration represents the buttons to be displayed on a MessageBox and has following values.
- OK
- OKCancel
- AbortRetryIgnore
- YesNoCancel
- YesNo
- RetryCancel
The following code snippet creates a MessageBox with a title and Yes and No buttons. This is a typical MessageBox you may call when you want to close an application. If the Yes button is clicked, the application will be closed. The Show method returns a DialogResult enumeration.
- string message = «Do you want to close this window?»;
- string title = «Close Window»;
- MessageBoxButtons buttons = MessageBoxButtons.YesNo;
- DialogResult result = MessageBox.Show(message, title, buttons);
- if (result == DialogResult.Yes) {
- this.Close();
- } else {
- }
MessageBox with Icon
A MessageBox can display an icon on the dialog. A MessageBoxIcons enumeration represents an icon to be displayed on a MessageBox and has the following values.
- None
- Hand
- Question
- Exclamation
- Asterisk
- Stop
- Error
- Warning
- Information
The following code snippet creates a MessageBox with a title, buttons, and an icon.
- string message = «Do you want to abort this operation?»;
- string title = «Close Window»;
- MessageBoxButtons buttons = MessageBoxButtons.AbortRetryIgnore;
- DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Warning);
- if (result == DialogResult.Abort) {
- this.Close();
- }
- elseif(result == DialogResult.Retry) {
- }
- else {
- }

MessageBox with Default Button
We can also set the default button on a MessageBox. By default, the first button is the default button. The MessageBoxDefaultButton enumeration is used for this purpose and it has the following three values.
- Button1
- Button2
- Button3
The following code snippet creates a MessageBox with a title, buttons, and an icon and sets the second button as a default button.
- string message = «Do you want to abort this operation?»;
- string title = «Close Window»;
- MessageBoxButtons buttons = MessageBoxButtons.AbortRetryIgnore;
- DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
- if (result == DialogResult.Abort) {
- this.Close();
- }
- elseif(result == DialogResult.Retry) {
- }
- else {
- }
MessageBox with Message Options
MessageBoxOptions enumeration represents various options and has the following values.
- ServiceNotification
- DefaultDesktopOnly
- RightAlign
- RtlReading
The following code snippet creates a MessageBox with various options.
- DialogResult result = MessageBox.Show(message, title, buttons,
- MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2,
- MessageBoxOptions.RightAlign|MessageBoxOptions.RtlReading);
MessageBox with Help Button
A MessageBox can have an extra button called Help button. This is useful when we need to display a help file. The following code snippet creates a MessageBox with a Help button.
- DialogResult result = MessageBox.Show(message, title, buttons,
- MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2,
- MessageBoxOptions.RightAlign, true );
We can also specify a help file when the Help button is clicked. The following code snippet references a help file.
- DialogResult result = MessageBox.Show(message, title,
- buttons, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, 0, «helpfile.chm»);
Summary
In this article, we discussed how to create and use a MessageBox in a Windows Forms application.
Мне нужно изменить заголовок по умолчанию для MsgBox окно сообщения во время выполнения. В настоящее время он постоянно показывает стоимость SetupAppTitle директива как заголовок:
[Setup]
SetupAppTitle=myAppName
Но это указывается во время компиляции. Как это сделать во время выполнения, например, из [Code] раздел ?
2 ответы
Я не думаю, что изменение заголовка приложения (если возможно) было бы хорошей идеей только для отображения заголовка диалога. Так что я бы использовал Windows MessageBox который даже используется MsgBox. Вот простой пример для Ansi / Unicode версий Inno Setup:
[Code]
const
MB_ICONERROR = $10;
MB_ICONQUESTION = $20;
MB_ICONWARNING = $30;
MB_ICONINFORMATION = $40;
#ifdef UNICODE
#define AW "W"
#else
#define AW "A"
#endif
function MessageBox(hWnd: HWND; lpText, lpCaption: string;
uType: UINT): Integer; external 'MessageBox{#AW}@user32.dll stdcall';
procedure ButtonOnClick(Sender: TObject);
begin
MessageBox(0, 'Message Text', 'Message Caption', MB_OK or MB_ICONINFORMATION);
end;
Создан 25 сен.
Вот как я наконец это сделал:
[Code]
{ https://msdn.microsoft.com/en-us/library/windows/desktop/ms645505.aspx }
{ Use Windows MessageBox() function as an MsgBox() replacement. }
{ MessageBoxW is the UNICODE version of this API call. }
const
{ these are not exported in Inno Setup! }
MB_ICONERROR = $00000010;
MB_ICONWARNING = $00000030;
MB_ICONINFORMATION = $00000040;
MB_ICONQUESTION = $00000020;
function _MessageBoxW_(hWnd: Integer; lpText, lpCaption: String; uType: Cardinal): Integer;
external 'MessageBoxW@user32.dll stdcall';
{ Usage: SysMsgBox('Error', 'Shit happens!', MB_OK or MB_ICONERROR); }
{ res =: SysMsgBox('Question', 'blah blah', MB_YESNO or MB_ICONQUESTION); }
function SysMsgBox(const Caption, Message: String; const Flags: Integer): Integer;
begin
Result :=
_MessageBoxW_(StrToInt(ExpandConstant('{wizardhwnd}')), Message, Caption, Flags);
end;
Спасибо всем за помощь!
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками
inno-setup
msgbox
or задайте свой вопрос.
Introduction to C# MessageBox
In today’s applications, it is always required that a message is displayed to the user as a token of information or confirmation so that the user is aware of the status of the operation he performed. The message can be anything ranging from “The payment is successful” or a warning type like “Do you want to continue” etc. This is achieved in C# with the help of Message Box. A message box can be considered as an interface between the user and the application. It is nothing but a window that has text, images, or symbols to guide or convey something to the user. Until appropriate action is performed, and the message box is closed, it will not allow other actions to be performed.
Syntax:
Message Box is a class in the “Systems.Windows.Forms” Namespace and the assembly it is available is “System.Windows.Forms.dll”.The show method available in the class is used to display the message along with action buttons. The action buttons can be anything ranging from Yes to No, Ok to Cancel.
Example:
The following code will create a simple Message Box only with the OK button.
string msg = "Test";
MessageBox.Show(msg);
Types of Show Methods
Following are the types of show method:
| Syntax | Use |
| MessageBox.Show(String) | It will display only the message box with the string that is passed. An ok button is also present to close the dialog. Example:
|
| MessageBox.Show( String, String) | It will display only the message box with the string that is passed as first parameter. The second parameter is the title of the Message Box. An ok button is also present to close the dialog. Example:
|
| MessageBox.Show( String,String, MessageBoxButtons) | It will display the message box with the supplied text, title and the corresponding buttons to be displayed on the Message Box. For eg the below will display Yes and No buttons.
|
| Show(String, String, MessageBoxButtons, MessageBoxIcon) | It will display the message box with the supplied text, title and the corresponding buttons to be displayed on the Message Box. It will also display the icon that is specified before the text. For eg the below will display Yes and No buttons with a question mark in front of message.
|
| Show(String, String, MessageBoxButtons, MessageBoxIcon, MessageBoxDefaulButton) | It will display the message box with the supplied text, title and the corresponding buttons to be displayed on the Message Box. It will also display the icon that is specified before the text. The last parameter denotes which button must be selected by default on load. For eg the below will display Yes and No buttons with a question mark in front of message.
|
| Show(String, String, MessageBoxButtons, MessageBoxIcon, MessageBoxDefaulButton, MessageBoxOptions) | It will display the message box with the supplied text, title, and the corresponding buttons to be displayed on the Message Box. It will also display the icon that is specified before the text. The last parameter denotes which button must be selected by default on load and the contents of the messagebox will be right-aligned. For eg the below will display Yes and No buttons with a question mark in front of message.
|
Types of MessageBox Buttons
The following are the types of Buttons that are available in the MessageBox.Show() method. They are
- OK: It is defined as MessageBoxButtons.OK
- OK and Cancel: It is defined as MessageBoxButtons.OkCancel.
- Abort Retry and Ignore: It is defined as MessageBoxButtons.AbortRetryIgnore.
- Yes No and Cancel: It is defined as MessageBoxButtons.YesNoCancel.
- Yes and No: It is defined as MessageBoxButtons.YesNo.
- Retry and Cancel: It is defined as MessageBoxButtons.RetryCancel.
Types of MessageBox Icons
The following are the types of MessageBox icons method are:
- None: No icons are displayed in the Message box.
- Hand: A hand icon is displayed. It is defined as MessageBoxIcon.Hand.
- Question: A question mark is displayed. It is defined as MessageBoxIcon.Question.
- Exclamation: An exclamation mark is displayed. It is defined as MessageBoxIcon.Exclamation.
- Asterisk: An asterisk symbol is displayed. It is defined as MessageBoxIcon.Asterisk.
- Stop: A stop icon is displayed. It is defined as MessageBoxIcon.Stop.
- Error: An error icon is displayed. It is defined as MessageBoxIcon.Error.
- Warning: A warning icon is displayed. It is defined as MessageBoxIcon.Warning.
- Information: An info symbol is displayed. It is defined as MessageBoxIcon.Information.
Types of MessageBox Options
The following are the various Message Box options that are available.
- ServiceNotification: It is defined as MessageBoxOptions.ServiceNotification. This is used to display the message box on the current desktop which is active. The message box is displayed even when no user is logged on to the desktop.
- DefaultDesktopOnly: It is defined as MessageBoxOptions.DefaultDesktopOnly. This also displays on the currently active desktop. The difference between this and service notification is that here the message is displayed on the interactive window.
- RightAlign: It is defined as MessageBoxOptions.RightAlign. This is used to format the message in right alignment.
- RtlReading: It is defined as MessageBoxOptions.RtlReading. This denotes that message is displayed from right to left order.
Example of C# MessageBox
Following are the examples of c# message box are:
Input:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace test
{
public partial class testform : Form
{
public testform()
{
InitializeComponent();
}
private void testform_Load(object sender, EventArgs e)
{
MessageBox.Show("Demo of MsgBox");
MessageBox.Show("Demo of MsgBox", "Title");
MessageBox.Show("Demo of Msgbox","Title",MessageBoxButtons.YesNo);
MessageBox.Show("Demo of Msgbox","Title",MessageBoxButtons.YesNoCancel);
MessageBox.Show("Demo of Msgbox","Title",MessageBoxButtons.OkCancel);
MessageBox.Show("Demo of Msgbox","Title",MessageBoxButtons.RetryCancel);
MessageBox.Show("Demo of Msgbox","Title",MessageBoxButtons.OK);
MessageBox.Show("Demo of Msgbox","Title",MessageBoxButtons.AbortRetryIgnore);
MessageBox.Show("Demo of Msgbox","Title",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Question);
MessageBox.Show("Demo of Msgbox","Title",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Hand);
MessageBox.Show("Demo of Msgbox","Title",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Exclamation);
MessageBox.Show("Demo of Msgbox","Title",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Asterisk);
MessageBox.Show("Demo of Msgbox","Title",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Stop);
MessageBox.Show("Demo of Msgbox","Title",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Error);
MessageBox.Show("Demo of Msgbox","Title",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Warning);MessageBox.Show("Demo of Msgbox","Title",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Information);MessageBox.Show("Demo of Msgbox","Title",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Question,MessageBoxDefaultButton.Button2);
MessageBox.Show("Demo of Msgbox","Title",MessageBoxButtons.OK,MessageBoxIcon.Exclamation,MessageBoxDefaultButton.Button1);
}
}
}
Output:
Conclusion – C# MessageBox
Thus, the article covered in detail about the Message box class in c# in detail. It explained about various message box show methods that are available, the various parameters of each method, and demonstrated that with an example. The article also covered in detail about various message box options, message box buttons, and message box icons in detail along with their use. To learn more in detail it is advisable to write sample programs and practice them.
Recommended Articles
This is a guide to C# MessageBox. Here we also discuss the introduction and types of show method along with an example and its code implementation. You may also have a look at the following articles to learn more –
- Assert in C#
- C# List vs Array
- ASP.NET CheckBox
- C# BinaryReader

Сообщение было отмечено dimazhelek как решение

я как-то не пытался редактировать текст и всегда ставил «Ок»












