基于VisualStudio11开发Windows8的Met

我们所了解的MessageBox。

函数原型:essageBox.Show(Text,Title,MessageBoxButtons,MessageBoxIcon ,MessageBoxDefaultButtons)  

参数说明:   

(1)Text:必选项,消息框的正文。   

(2)Title:可选项,消息框的标题。   

(3)MessageBoxButtons:可选项,消息框的按钮设置,默认只显示【确定】按钮。   

OK――确定 OKCancel――确定和取消 AbortRetryIgnore――终止、重试和忽略 YesNoCancel――是、否和取消 YesNo――是和否 RetryCancel――重试和取消

(4)MessageBoxIcon:对话框中显示的图标样式,默认不显示任何图标。 Question――问号 Information、Asterisk――i号 Error、Stop、Hand――错误号Warning、Exclamation――!号 None――不显示任何图标   

(5)MessageBoxDefaultButtons:可选项,对话框中默认选中的按钮设置。DefaultButton1――第1个button是默认按钮   DefaultButton2――第2个button是默认按钮   DefaultButton3――第3个button是默认按钮   

备注:函数原型中蓝色字体部分的参数,可以通过点来获取其后面跟随的参数值。

MessageBox(NULL,"text","title",BUTTON);

参数title:string类型,指定消息对话框的标题。text:指定消息对话框中显示的消息,该参数可以是数值数据类型、字符串或boolean值。icon:Icon枚举类型,可选项,指定要在该对话框左侧显示的图标。button:Button枚举类型,可选项,指定显示在该对话框底部的按钮。default:数值型,可选项,指定作为缺省按钮的按钮编号,按钮编号自左向右依次计数,缺省值为1,如果该参数指定的编号超过了显示的按钮个数,那么MessageBox()函数将使用缺省值返回值Integer。函数执行成功时返回用户选择的按钮编号(例如1、2、3等),发生错误时返回-1。如果任何参数的值为NULL,MessageBox()函数返回NULL。 
比如说,想弹出如图所示的窗口,命令为: MessageBox(NULL,"MessageBoxText(内容)","Title(标题)",MB_OK); 如果想置顶   int iRet; iRet=MessageBox(hwnd,"PLC报警!","对话框",MB_YESNO|MB_ICONQUESTION|MB_SYSTEMMODAL);   或 iRet=MessageBox(NULL,"PLC报警!","对话框", MB_YESNO|MB_ICONQUESTION|MB_DEFBUTTON1|MB_SYSTEMMODAL); 增加一个焦点在第一个按钮上更有效。

参数如下

hWnd:标识将被创建的消息框的拥有窗口。如果此参数为NULL,则消息框没有拥有窗口。

lpText:指向一个以NULL结尾的、含有将被显示的消息的字符串的指针。

lpCaption:指向一个以NULL结尾的、用于对话框标题的字符串的指针。

uType:指定一个决定对话框的内容和行为的位标志集。此参数可以为下列标志组中标志的组合。

指定下列标志中的一个来显示消息框中的按钮,标志的含义如下。

MB_ABORTRETRYIGNORE:消息框含有三个按钮:Abort,Retry和Ignore。

MB_OK:消息框含有一个按钮:OK。这是缺省值。

MB_OKCANCEL:消息框含有两个按钮:OK和Cancel。

MB_RETRYCANCEL:消息框含有两个按钮:Retry和Cancel。

MB_YESNO:消息框含有两个按钮:Yes和No。

MB_YESNOCANCEL:消息框含有三个按钮:Yes,No和Cancel。

指定下列标志中的一个来显示消息框中的图标:标志的含义如下。

MB_ICONEXCLAMATION:

MB_ICONWARNING:一个惊叹号出现在消息框。

MB_ICONINFORMATION:

MB_ICONASTERISK:一个圆圈中小写字母i组成的图标出现在消息框。

MB_ICONQUESTION:一个问题标记图标出现在消息框。

MB_ICONSTOP:

MB_ICONERROR:

MB_ICONHAND:一个停止消息图标出现在消息框。

指定下列标志中的一个来显不缺省的按钮:标志的含义如下。

MB_DEFBUTTON1:第一个按钮为缺省按钮。如果MB_DEFBUTTON2,MB_DEFBUTTON3,MB_DEFBUTTON4没有被指定,则MB_DEFBUTTON1为缺省值。

MB_DEFBUTTON2;第二个按钮为缺省按钮。

MB_DEFBUTTON3:第三个按钮为缺省按钮。

MB_DEFBUTTON4:第四个按钮为缺省按钮。

指定下列标志中的一个来显示对话框的形态:标志的含义如卜。

MB_APPLMODAL:在hwnd参数标识的窗口中继续工作以前,用户一定响应消息框。但是,用户可以移动到其他线程的窗口且在这些窗口中工作。根据应用程序中窗口的层次机构,用户则以移动到线程内的其他窗口。所有母消息框的子窗口自动地失效,但是弹出窗口不是这样。如果既没有指定MB_SYSTEMMODAL也没有指定MB_TASKMOOAL,则MB_APPLMODAL为缺省的。

MB_SYSTEMMODAL:除了消息框有WB_EX_TOPMOST类型,MB_APPLMODAL和WS_EX_TOPMOST一样。用系统模态消息框来改变各种各样的用户,主要的损坏错误需要立即注意(例如,内存溢出)。如果不是那些与hwnd联系的窗口,此标志对用户对窗口的相互联系没有影响。

MB_TASKMODAL:如果参数hwnd为NULL,除了所有属于当前线程高层次的窗口足失效的,MB_TASKMODALL和MB_ApPLMODAL一样。当调用应用程序或库没有一个可以得到的窗口句柄时,使用此标志。但仍需要阻止到调用应用程序甲其他窗口的输入而不是搁置其他线程。

另外,可以指定下列标志。

MB_DEFAULT_DESKTOP_ONLy:接收输入的当前桌面一定是一个缺省桌面。否则,函数调用失败。缺省桌面是一个在用户已经纪录且以后应用程序在此上面运行的桌面。

MB_HELP:把一个Help按钮增加到消息框。选择Help按钮或按F1产生一个Help事件。

MB_RIGHT:文本为右调整。

MB_RTLREADING:用在Hebrew和Arabic系统中从右到左的顺序显示消息和大写文本。

MB_SETFOREGROUND:消息框变为前景窗口。在内部系统为消息个调用SetForegroundWindow函数。

MB_TOPMOSI:消息框用WS_EX_TOPMOST窗口类型来创建MB_SERVICE_NOTIFICATION。

Windows NT:调用程序是一个通知事件的用户的服务程序。函数在当前活动桌面上显示一个消息框,即使没有用户登记到计算机。

如果设置了此参数,则hwnd参数一定为NULL。所以消息框可以出现在一个桌面上而不是桌面响应参数hwnd。

对于Windows NT 4.0,MB_SERVICE_NOTIFICATION的值已经改变。对于旧的和新的值,请参见WINUSER。

Windows NT 4.O通过把旧值映射到MessageBox和MessageBoxEx执行中的新值,为先存在的服务程序提供逆兼容。此映射只为有了版本数目的可执行程序而做。

为了建立一个用MB_SERVICE_NOTIFICATION的服务器,且可以在Windows NT 3.X和Window NT 4.0上执行,可有两种选择。在连接时间,指定一个版本数目小于4.0的版本,或在连接时间,指定一个4.0版本。在运行时间,用函数GetVersionEx来检测系统版本,然后在Windows NT 3.X上用MB_SERVICE_NOTIFICATION_NT 3.x来运行和在Windows NT 4.0上用MB_SERVICE_NOTIFICAION来运行。MB_SERVCE_NOTIFICATION_NT3.x(WindowNT)此值响应于为WindowNT3.51的MB_SERVICE_NOTIFICAION

定义的值。

返回值如下

如果没有足够的内存来创建消息框,则返回值为零。如果函数调用成功,则返回值为下列对话框返回的菜单项目值中的一个:

IDABORT:Abort 按钮被选中。IDCANCEL:Cancel按钮被选中。IDIGNORE:Ignore按钮被选中。

IDNO:NO按钮被选中。IDOK:OK按钮被选中。IDRETRY:RETRY按钮被选中。

IDYES:YES按钮被选中。

如果一个消息框有一个Cancel按钮,且如果Esc键被按下或Cancel键被选择,则函数返回IDCANCEL值。如果消息框没有Cancel按钮,则按Esc键没有作用。

MessageBox的返回值默认定义 MessageBox的返回值其实都是整型的数,以下是默认的定义

  #define IDOK 1

  #define IDCANCEL 2

  #define IDABORT 3

  #define IDRETRY 4

  #define IDIGNORE 5

  #define IDYES 6

  #define IDNO 7

  #if(WINVER >= 0x0400)

  #define IDCLOSE 8

  #define IDHELP 9

下面我们来亲自实践Windows8中的MessageBox

看一下程序初始化代码

#include "pch.h"
#include "MainPage.xaml.h"
#include "App.xaml.h"

using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::System;
using namespace Windows::Foundation;
using namespace Platform;
using namespace MessageDialog;
using namespace CppSamplesUtils;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::UI::Xaml::Interop;
using namespace Windows::UI::ViewManagement;
using namespace Windows::Graphics::Display;

MainPage::MainPage()
{
    InitializeComponent();

    SetFeatureName("MessageDialog");

    _scenariosFrame = ScenarioList;
    _inputFrame = ScenarioInput;
    _outputFrame = ScenarioOutput;

    _layoutHandlerToken = ApplicationView::GetForCurrentView()->ViewStateChanged +=
    ref new TypedEventHandler<ApplicationView^, ApplicationViewStateChangedEventArgs^>(this, &MainPage::Page_ViewStateChanged);

    _pageLoadedHandlerToken = Loaded += ref new RoutedEventHandler(this, &MainPage::Page_Loaded);
    _logicalDpiChangedToken = DisplayProperties::LogicalDpiChanged += ref new DisplayPropertiesEventHandler(this, &MainPage::DisplayProperties_LogicalDpiChanged);

}

MainPage::~MainPage()
{
}

void MainPage::Page_Loaded(Object^ sender, RoutedEventArgs^ e)
{
        TypeName pageType = { "MessageDialog.ScenarioList", TypeKind::Custom };
    ScenarioList->Navigate(pageType, this);

    CheckResolutionAndViewState();
}

void MainPage::SetFeatureName(String^ strFeature)
{
    FeatureName->Text = strFeature;
}

void MainPage::Page_ViewStateChanged(ApplicationView^ sender, ApplicationViewStateChangedEventArgs^ e)
{
    CheckResolutionAndViewState();
}

void MainPage::DisplayProperties_LogicalDpiChanged(Object^ sender)
{
    CheckResolutionAndViewState();
}

void MainPage::CheckResolutionAndViewState()
{
    ::ApplicationViewState state = ApplicationView::Value;
    String^ stateString = ConvertViewState(state);

    ::ResolutionScale scale = DisplayProperties::ResolutionScale;
    String^ scaleString = ConvertResolution(scale);

    VisualStateManager::GoToState(this, stateString + scaleString, false);
}

String^ MainPage::ConvertViewState(::ApplicationViewState state)
{
    switch (state)
    {
    case ::ApplicationViewState::Filled:
        return "Filled";
    case ::ApplicationViewState::FullScreenLandscape:
        return "FullScreenLandscape";
    case ::ApplicationViewState::FullScreenPortrait:
        return "FullScreenPortrait";
    case ::ApplicationViewState::Snapped:
        return "Snapped";
    }
    return "";
}

String^ MainPage::ConvertResolution(::ResolutionScale scale)
{
    switch (scale)
    {
    case ::ResolutionScale::Scale100Percent:
        return "Scale100Percent";
    case ::ResolutionScale::Scale140Percent:
        return "Scale140Percent";
    case ::ResolutionScale::Scale180Percent:
        return "Scale180Percent";
    }
    return "";
}

void MainPage::DoNavigation(TypeName pageType, ::Frame^ frame)
{
    frame->Navigate(pageType, this);

    std::wstring PageName(pageType.Name->Data());
    std::basic_string <wchar_t>::size_type indexSubstring;
    indexSubstring = PageName.find(L"Output");
    if (indexSubstring != std::wstring::npos)
    {
               if (OutputFrameLoaded != nullptr)
        {
            OutputFrameLoaded(this, nullptr);
        }
    }
    else
    {

        if (InputFrameLoaded != nullptr)
        {
            InputFrameLoaded(this, nullptr);
        }
    }
}

void MainPage::NotifyUser(String^ strMessage, NotifyType type)
{
    switch (type)
    {
    case NotifyType::StatusMessage:
        StatusBlock->Style = dynamic_cast<::Style^>(App::Current->Resources->Lookup("StatusStyle"));
        break;
    case NotifyType::ErrorMessage:
        StatusBlock->Style = dynamic_cast<::Style^>(App::Current->Resources->Lookup("ErrorStyle"));
        break;
    default:
        break;
    }
    StatusBlock->Text = strMessage;
}

void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
{
    auto _hyperlinkButton = (HyperlinkButton^)sender;
    auto uri = ref new ::Uri((String^)_hyperlinkButton->Tag);

    ::Launcher::LaunchUriAsync(uri);
}

对话框1

#pragma region Click handlers
void ScenarioInput1::Scenario1Launch_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
     Windows::UI::Popups::MessageDialog^ msg = ref new Windows::UI::Popups::MessageDialog("You"ve exceeded your trial period.");

    IAsyncOperation<IUICommand^>^ operation = msg->ShowAsync();

     operation->Completed = ref new AsyncOperationCompletedHandler<IUICommand^>([this](IAsyncOperation<IUICommand^>^ op, AsyncStatus status)
    {
        if (status == AsyncStatus::Completed)
        {
            this->NotifyUserHandler();
            op->Close();
        }
        else
        {
            rootPage->NotifyUser("Message dialog returned an error", NotifyType::StatusMessage);
        }
    });    
}

void ScenarioInput1::NotifyUserHandler()
{
    InvokedHandler^ callback = ref new InvokedHandler([this](Object^ sender, IInvokedHandlerArgs^ eInvoke)
    {
        rootPage->NotifyUser("The dialog has now been closed", NotifyType::StatusMessage);
    });

    Dispatcher->InvokeAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, callback, this, nullptr);
}
#pragma endregion

对话框2

using namespace MessageDialog;
using namespace Windows::UI::Core;
using namespace Windows::UI::Popups;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::Foundation;
using namespace Platform;

ScenarioInput2::ScenarioInput2()
{
    InitializeComponent();
}

ScenarioInput2::~ScenarioInput2()
{
}
void ScenarioInput2::OnNavigatedTo(NavigationEventArgs^ e)
{
       rootPage = dynamic_cast<MainPage^>(e->Parameter);

    _frameLoadedToken = rootPage->OutputFrameLoaded += ref new Windows::Foundation::EventHandler<Platform::Object^>(this, &ScenarioInput2::rootPage_OutputFrameLoaded);
}

void ScenarioInput2::OnNavigatedFrom(NavigationEventArgs^ e)
{
    rootPage->OutputFrameLoaded -= _frameLoadedToken;
}
#pragma endregion

#pragma region Output frame
void ScenarioInput2::rootPage_OutputFrameLoaded(Object^ sender, Object^ e)
{
    // Get a pointer to the content within the OutputFrame
    Page^ outputFrame = dynamic_cast<Page^>(rootPage->OutputFrame->Content);
}
#pragma endregion

#pragma region Click handlers
void ScenarioInput2::Scenario2Launch_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
       Windows::UI::Popups::MessageDialog^ msg = ref new Windows::UI::Popups::MessageDialog("You have exceeded your trial period. Would you like to continue your trial or upgrade to the full version?");

      UICommand^ continueCommand = ref new UICommand("Continue trial", ref new UICommandInvokedHandler(this, &ScenarioInput2::CommandInvokedHandler, CallbackContext::Same));
    UICommand^ upgradeCommand = ref new UICommand("Upgrade", ref new UICommandInvokedHandler(this, &ScenarioInput2::CommandInvokedHandler, CallbackContext::Same));

    msg->Commands->Append(continueCommand);
    msg->Commands->Append(upgradeCommand);

    msg->ShowAsync();
}

void ScenarioInput2::CommandInvokedHandler(Windows::UI::Popups::IUICommand^ command)
{
    String ^buttonLabel = command->Label;
    rootPage->NotifyUser("The "" + buttonLabel + "" button has been selected.", NotifyType::StatusMessage);
}
#pragma endregion

 

对话框3

using namespace MessageDialog;
using namespace Windows::UI::Popups;
using namespace Windows::UI::Xaml::Navigation;
using namespace Platform;

ScenarioInput3::ScenarioInput3()
{
    InitializeComponent();
}

ScenarioInput3::~ScenarioInput3()
{
}

void ScenarioInput3::OnNavigatedTo(NavigationEventArgs^ e)
{
     rootPage = dynamic_cast<MainPage^>(e->Parameter);

    _frameLoadedToken = rootPage->OutputFrameLoaded += ref new Windows::Foundation::EventHandler<Platform::Object^>(this, &ScenarioInput3::rootPage_OutputFrameLoaded);
}

void ScenarioInput3::OnNavigatedFrom(NavigationEventArgs^ e)
{
    rootPage->OutputFrameLoaded -= _frameLoadedToken;
}
#pragma endregion

#pragma region Output frame
void ScenarioInput3::rootPage_OutputFrameLoaded(Object^ sender, Object^ e)
{
    Page^ outputFrame = dynamic_cast<Page^>(rootPage->OutputFrame->Content);
}
#pragma endregion

#pragma region Click handlers
void ScenarioInput3::Scenario3Launch_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
    Windows::UI::Popups::MessageDialog^ msg = ref new Windows::UI::Popups::MessageDialog("Would you like to install the new updates?", "Updates available");
    UICommand^ noInstallCommand = ref new UICommand("Don"t install", ref new UICommandInvokedHandler(this, &ScenarioInput3::CommandInvokedHandler, CallbackContext::Same));
    UICommand^ installCommand = ref new UICommand("Install updates", ref new UICommandInvokedHandler(this, &ScenarioInput3::CommandInvokedHandler, CallbackContext::Same));

    msg->Commands->Append(noInstallCommand);
    msg->Commands->Append(installCommand);

    msg->DefaultCommandIndex = 1;

    msg->ShowAsync();
}
void ScenarioInput3::CommandInvokedHandler(Windows::UI::Popups::IUICommand^ command)
{
    String ^buttonLabel = command->Label;
    rootPage->NotifyUser("The "" + buttonLabel + "" button has been selected.", NotifyType::StatusMessage);
}
#pragma endregion

 

对话框4

using namespace MessageDialog;
using namespace Windows::UI::Popups;
using namespace Windows::UI::Xaml::Navigation;
using namespace Platform;

ScenarioInput4::ScenarioInput4()
{
    InitializeComponent();
}

ScenarioInput4::~ScenarioInput4()
{
}

#pragma region Template-Related Code - Do not remove
void ScenarioInput4::OnNavigatedTo(NavigationEventArgs^ e)
{
       rootPage = dynamic_cast<MainPage^>(e->Parameter);

      _frameLoadedToken = rootPage->OutputFrameLoaded += ref new Windows::Foundation::EventHandler<Platform::Object^>(this, &ScenarioInput4::rootPage_OutputFrameLoaded);
}

void ScenarioInput4::OnNavigatedFrom(NavigationEventArgs^ e)
{
    rootPage->OutputFrameLoaded -= _frameLoadedToken;
}
#pragma endregion

#pragma region Output frame
void ScenarioInput4::rootPage_OutputFrameLoaded(Object^ sender, Object^ e)
{
    Page^ outputFrame = dynamic_cast<Page^>(rootPage->OutputFrame->Content);
}
#pragma endregion

#pragma region Click handlers
void ScenarioInput4::Scenario4Launch_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
    Windows::UI::Popups::MessageDialog^ msg = ref new Windows::UI::Popups::MessageDialog("You have been disconnected from the internet.");

    UICommand^ closeCommand = ref new UICommand("Retry", ref new UICommandInvokedHandler(this, &ScenarioInput4::CommandInvokedHandler, CallbackContext::Same));
    UICommand^ retryCommand = ref new UICommand("Close", ref new UICommandInvokedHandler(this, &ScenarioInput4::CommandInvokedHandler, CallbackContext::Same));

       msg->Commands->Append(closeCommand);
    msg->Commands->Append(retryCommand);
    msg->CancelCommandIndex = 1;

    msg->ShowAsync();
}
void ScenarioInput4::CommandInvokedHandler(Windows::UI::Popups::IUICommand^ command)
{
    String ^buttonLabel = command->Label;
    rootPage->NotifyUser("The "" + buttonLabel + "" button has been selected.", NotifyType::StatusMessage);
}

#pragma endregion

按下F5看运行效果

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

赶紧下载VS11体验吧

http://www.microsoft.com/click/services/Redirect2.ashx?CR_CC=200098144

 

 

 

 

文章导航