C#/WPF 只允许一个实例程序运行并将已运行程序置顶

50 篇文章 18 订阅

使用用互斥量(System.Threading.Mutex):
    同步基元,它只向一个线程授予对共享资源的独占访问权。在程序启动时候,请求一个互斥体,如果能获取对指定互斥的访问权,就职运行一个实例。

实例代码:

    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        [DllImport("user32.dll ")]
        //设置窗体置顶
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("User32.dll")]
        public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        private static Mutex _m = null;
        private static string currentProcess = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
        /// <summary>
        /// 只允许运行一个实例
        /// </summary>
        /// <param name="mutexName"></param>
        /// <returns>true:已经存在实例 false:不存在实例</returns>
        public static bool CheckRunOneInstance(string mutexName = null)
        {

            bool result = false;
            bool mutexWasCreated = false;
            try
            {
                bool requestInitialOwnership = true;
                if (mutexName == null)
                    mutexName = currentProcess;
                _m = new Mutex(requestInitialOwnership, mutexName, out mutexWasCreated);
                if (!mutexWasCreated)
                {
                    result = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return result;
        }

        /// <summary>
        /// 有程序运行,设置焦点
        /// </summary>
        private void Focus()
        {
            foreach (Process process in Process.GetProcesses())
            {
                try
                {
                    if (process.ProcessName.ToLower() != currentProcess.ToLower())
                        continue;
                    IntPtr hwnd = process.MainWindowHandle;
                    if (hwnd != IntPtr.Zero)
                    {
                        SetForegroundWindow(hwnd);
                        ShowWindow(hwnd, 2);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            if(CheckRunOneInstance())
            {
                Focus();
                System.Windows.Application.Current.Shutdown();
                return;
            }
            else
            {
                new MainWindow().Show();
            }
        }
    }

实例链接:

https://download.csdn.net/download/lvxingzhe3/88668552

  • 8
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,以下是一个使用WPF框架设计的计算BMI值的程序: 首先,我们需要在XAML中设计用户界面。在这里,我们将使用两个文本框和一个按钮来允许用户输入体重和身高,然后计算BMI值并显示结果。 ```xaml <Window x:Class="BMICalculator.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="BMI Calculator" Height="250" Width="300"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Label Grid.Row="0" Content="Weight (kg):"/> <TextBox Grid.Row="0" Name="weightTextBox" Margin="5,0,0,0" /> <Label Grid.Row="1" Content="Height (m):"/> <TextBox Grid.Row="1" Name="heightTextBox" Margin="5,0,0,0" /> <Button Grid.Row="2" Content="Calculate BMI" Name="calculateButton" Margin="5,10,5,0" Click="CalculateButton_Click"/> <Label Grid.Row="3" Name="bmiResultLabel" Margin="5,10,5,5"/> </Grid> </Window> ``` 然后,我们需要编写C#代码来计算BMI值并将其显示在标签中。在这个例子中,我们将在单击“计算BMI”按钮时执行计算,并将结果显示在一个标签中。 ```csharp using System; using System.Windows; namespace BMICalculator { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void CalculateButton_Click(object sender, RoutedEventArgs e) { try { double weight = double.Parse(weightTextBox.Text); double height = double.Parse(heightTextBox.Text); double bmi = weight / (height * height); bmiResultLabel.Content = "Your BMI is: " + bmi.ToString("F2"); } catch (FormatException) { bmiResultLabel.Content = "Please enter valid numbers for weight and height."; } } } } ``` 这个程序很简单:当用户单击“计算BMI”按钮时,它将读取文本框中的体重和身高值,并使用这些值计算BMI。然后,它将BMI值显示在一个标签中。如果用户输入的不是数字,它将显示一个错误提示。 希望这可以帮助您开始编写BMI计算器。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无熵~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值