c# 设置winform程序为默认打开软件 在运行中获取参数

时间:2021-04-04 00:11:55

1.右键→打开方式→选择默认程序→选择winform程序

c# 设置winform程序为默认打开软件 在运行中获取参数

2.修改Program.cs

判断注册的事件是否存在,如果不存在则运行实例,并把参数传入MainForm里,如果存在则把参数写到txt文件中,然后发事件,退出

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Windows.Forms; namespace SimpleMusicPlayer
{
static class Program
{
public static EventWaitHandle ProgramStarted; /// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
// 尝试创建一个命名事件
bool createNew;
ProgramStarted = new EventWaitHandle(false, EventResetMode.AutoReset, "MyStartEvent", out createNew); // 如果该命名事件已经存在(存在有前一个运行实例),则发事件通知并退出
if (!createNew)
{
// 先写一些数据到txt中,以便传递给前一个运行实例
//Registry.SetValue(@"HKEY_CURRENT_USER\Software\MyMusic", "", string.Join(",", args));
string fileName = Application.StartupPath + "\\args.txt";
StreamWriter sw = new StreamWriter(fileName, false);
sw.WriteLine(args[]);//开始写入值
sw.Close(); ProgramStarted.Set();
return;
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm(args.Length==?null:args[]));
} } }
}

3.MainForm.cs

当收到第二个进程的通知时,读取txt中参数(MP3路径),显示窗体

     public MainForm(string param)
{
InitializeComponent(); if (param != null)
setFileName(param); ThreadPool.RegisterWaitForSingleObject(Program.ProgramStarted, OnProgramStarted, null, -, false);
} private void setFileName(string param)
{
//通过参数(mp3文件路径)获取mp3信息
} // 当收到第二个进程的通知时,显示窗体
private void OnProgramStarted(object state, bool timeout)
{
if (this.InvokeRequired)
{
this.Invoke(new WaitOrTimerCallback(OnProgramStarted), state, timeout);
}
else
{
string param = getArgs(Application.StartupPath + "\\args.txt");
if (param != null)
setFileName(param);
this.WindowState = FormWindowState.Normal;
}
} //读取txt文件中参数
private string getArgs(string fileName)
{
if (File.Exists(fileName))
{
//存在
StreamReader stream = new StreamReader(fileName, Encoding.UTF8);
string str = stream.ReadLine();
stream.Close();
return str;
}
else
{
return null;
}
}

4.打完收工

c# 设置winform程序为默认打开软件 在运行中获取参数

c# 设置winform程序为默认打开软件 在运行中获取参数