winform 文件关联测试项目 打开exe时传值args给exe调用

  • Program.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 文件关联测试项目
{
    static class Program
    {
        const int WM_COPYDATA = 0x004A;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            try
            {
                bool ret;
                System.Threading.Mutex mutex = new System.Threading.Mutex(true, Application.ProductName, out ret);
                if (ret)
                {
                    MessageBox.Show("dddd");
                    if (args != null && args.Length > 0)
                    {
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Application.Run(new Form1(args[0]));
                    }
                    else
                    {
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Application.Run(new Form1());
                    }
                    mutex.ReleaseMutex();
                    
                }
                else
                {
                    if (args != null && args.Length > 0)
                    {


                        int WINDOW_HANDLER = GetHandler();
                        if (WINDOW_HANDLER != 0)
                        {
                            byte[] sarr = System.Text.Encoding.Default.GetBytes(args[0]);
                            int len = sarr.Length;
                            COPYDATASTRUCT cds;
                            cds.dwData = (IntPtr)100;
                            cds.lpData = args[0];
                            cds.cbData = len + 1;
                            SendMessage(WINDOW_HANDLER, WM_COPYDATA, 0, ref cds);
                        }

                    }
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.ToString());
            }    
            


        }

        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(
           int hWnd, // handle to destination window
           int Msg, // message
           int wParam, // first message parameter
           ref COPYDATASTRUCT lParam // second message parameter
       );

        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        private static extern int FindWindow(string lpClassName, string lpWindowName);

        static int GetHandler()
        {
        	//"AAAA"是当前应用程序的窗口名称,找到当前要传值的exe程序的进程,打开时传值
            return FindWindow(null, "AAAA");
            foreach (var item in Process.GetProcesses())
            {
                if (item.MainModule.FileName == Application.ExecutablePath)
                {
                    return (int)item.MainWindowHandle;
                }
            }

            return 0;
        }
        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpData;
        }

    }
}

  • Form.cs
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 文件关联测试项目
{
    public partial class Form1 : Form
    {
        const int WM_COPYDATA = 0x004A;
        public Form1()
        {
            InitializeComponent();
            RegisterFileType(".b", null, null, System.Windows.Forms.Application.ExecutablePath);
        }

        public Form1(string arg)
        {
            InitializeComponent();
            
            richTextBox1.Text = arg;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Task task2 = new Task(() =>
            {
                while (true)
                {
                    if (actQueue.Count > 0)
                    {
                        DoUI(actQueue.Dequeue());
                    }
                    else
                    {
                        Thread.Sleep(1);
                    }
                }
            });
            task2.Start();
        }
        public void DoUI(Action cb)
        {
            this.Invoke(cb);
        }
        /// <summary>
        /// 检查一下文件类型是否已被注册.
        /// </summary>
        /// <param name="extension"></param>
        /// <returns></returns>
        public static bool FileTypeRegistered(string extension)
        {
            RegistryKey sluKey = Registry.ClassesRoot.OpenSubKey(extension);
            if (sluKey != null)
                return true;
            return false;
        }
        /// <summary>
        /// 删除已被注册的键值
        /// </summary>
        /// <param name="extension"></param>
        public static void UnRegistFileType(string extension)
        {
            if (FileTypeRegistered(extension))
            {
                Registry.ClassesRoot.DeleteSubKeyTree(extension);
                //string relationName = extension.Substring(1, extension.Length - 1).ToUpper() + "  FileType ";
                //Registry.ClassesRoot.DeleteSubKeyTree(relationName);
                Registry.ClassesRoot.Close();
            }
        }

        private static void RegisterFileType(string typeName,string fileType,string fileContent, string app)
        {
            //工具启动路径
            string toolPath = app;

            string extension = typeName;

            fileType = "自定义文件类型";

            fileContent = "AAAA";
            //获取信息
            RegistryKey registryKey = Registry.ClassesRoot.OpenSubKey(extension);

            if (registryKey != null && registryKey.OpenSubKey("shell") != null && registryKey.OpenSubKey("shell").OpenSubKey("open") != null &&
              registryKey.OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command") != null)
            {
                var varSub = registryKey.OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command");
                var varValue = varSub.GetValue("");

                if (Equals(varValue, toolPath + " \"%1\""))
                {
                    return;
                }
            }
            //删除
            Registry.ClassesRoot.DeleteSubKeyTree(extension, false);
            //文件注册
            registryKey = Registry.ClassesRoot.CreateSubKey(extension);
            registryKey.SetValue("", fileType);
            registryKey.SetValue("Content Type", fileContent);
            //设置默认图标
            RegistryKey iconKey = registryKey.CreateSubKey("DefaultIcon");
            //设置1.ico为文件的图标,如果没有自己找个
            iconKey.SetValue("", Application.StartupPath + "\\1.ico");
            iconKey.Close();
            //设置默认打开程序路径
            registryKey = registryKey.CreateSubKey("shell\\open\\command");
            registryKey.SetValue("", toolPath + " \"%1\"");
            //关闭
            registryKey.Close();

            SHChangeNotify(0x8000000, 0, IntPtr.Zero, IntPtr.Zero);
        }

        [DllImport("shell32.dll")]
        public static extern void SHChangeNotify(uint wEventId, uint uFlags, IntPtr dwItem1, IntPtr dwItem2);

        Queue<Action> actQueue = new Queue<Action>();
        protected override void DefWndProc(ref System.Windows.Forms.Message m)
        {
            switch (m.Msg)
            {
                case WM_COPYDATA:
                    COPYDATASTRUCT mystr = new COPYDATASTRUCT();
                    Type mytype = mystr.GetType();
                    mystr = (COPYDATASTRUCT)m.GetLParam(mytype);
                    //this.richTextBox1.Text = mystr.lpData;
                    actQueue.Enqueue(() =>
                    {
                        Loaded();
                    });

                    break;
                default:
                    base.DefWndProc(ref m);
                    break;
            }
        }
        private void Loaded()
        {
            //执行我自己的方法
            this.richTextBox1.Text = mystr.lpData;
        }
        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpData;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值