溫馨提示×

C#中如何實現(xiàn)彈窗提醒

c#
小樊
97
2024-09-08 02:12:36
欄目: 編程語言

在C#中,可以使用Windows Forms或WPF(Windows Presentation Foundation)來創(chuàng)建一個彈窗提醒。這里將分別介紹這兩種方法。

  1. 使用Windows Forms創(chuàng)建彈窗提醒:

首先,需要添加System.Windows.Forms的引用。然后,可以使用MessageBox類來顯示一個彈窗提醒。以下是一個簡單的示例:

using System;
using System.Windows.Forms;

namespace WindowsFormsApp
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // 顯示一個彈窗提醒
            DialogResult result = MessageBox.Show("這是一個彈窗提醒!", "提醒", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);

            // 根據(jù)用戶的選擇執(zhí)行相應的操作
            if (result == DialogResult.OK)
            {
                Console.WriteLine("用戶點擊了確定按鈕");
            }
            else if (result == DialogResult.Cancel)
            {
                Console.WriteLine("用戶點擊了取消按鈕");
            }
        }
    }
}
  1. 使用WPF創(chuàng)建彈窗提醒:

在WPF中,可以使用MessageBox類(需要添加System.Windows的引用)或者自定義一個窗口來實現(xiàn)彈窗提醒。以下是一個使用MessageBox類的簡單示例:

using System;
using System.Windows;

namespace WpfApp
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            // 顯示一個彈窗提醒
            MessageBoxResult result = MessageBox.Show("這是一個彈窗提醒!", "提醒", MessageBoxButton.OKCancel, MessageBoxImage.Information);

            // 根據(jù)用戶的選擇執(zhí)行相應的操作
            if (result == MessageBoxResult.OK)
            {
                Console.WriteLine("用戶點擊了確定按鈕");
            }
            else if (result == MessageBoxResult.Cancel)
            {
                Console.WriteLine("用戶點擊了取消按鈕");
            }
        }
    }
}

注意:在WPF項目中,需要添加對System.Windows.Forms的引用才能使用MessageBox類。在項目中右鍵單擊“引用”,然后選擇“添加引用”,在“程序集”選項卡下找到并添加System.Windows.Forms。

0