c# 自訂檔案關聯程式

來源:互聯網
上載者:User

      做很多程式都是獨立啟動並執行,然後做各種操作,今天嘗試一下像播放器之類的程式,我們自訂一些檔案類型,然後關聯自己的軟體。雙擊開啟時就將檔案傳入了軟體,同樣可以支援將檔案拖放到程式上運行。 閑話少說,下面開始寫程式,首先建立一個c#的winForm程式。然後解決檔案關聯問題,其實就是操作註冊表,在註冊表中記錄了檔案的類型和關聯的程式:

 

 

下面這段是從網上看到的代碼:

/// <summary>/// 關聯檔案/// </summary>/// <param name="_FilePathString">應用程式路徑</param>/// <param name="p_FileTypeName">檔案類型</param>public static void SaveReg(string _FilePathString,string p_FileTypeName){RegistryKey _RegKey = Registry.ClassesRoot.OpenSubKey("", true);              //開啟註冊表RegistryKey _VRPkey = _RegKey.OpenSubKey(p_FileTypeName, true);if (_VRPkey != null){_RegKey.DeleteSubKey(p_FileTypeName, true);}_RegKey.CreateSubKey(p_FileTypeName);_VRPkey = _RegKey.OpenSubKey(p_FileTypeName, true);_VRPkey.SetValue("", "Exec");_VRPkey = _RegKey.OpenSubKey("Exec", true);if (_VRPkey != null) _RegKey.DeleteSubKeyTree("Exec");         //如果等於空就刪除註冊表DSKJIVR_RegKey.CreateSubKey("Exec");_VRPkey = _RegKey.OpenSubKey("Exec", true);_VRPkey.CreateSubKey("shell");_VRPkey = _VRPkey.OpenSubKey("shell", true);                      //寫入必須路徑_VRPkey.CreateSubKey("open");_VRPkey = _VRPkey.OpenSubKey("open", true);_VRPkey.CreateSubKey("command");_VRPkey = _VRPkey.OpenSubKey("command", true);string _PathString = "\"" + _FilePathString + "\" \"%1\"";_VRPkey.SetValue("", _PathString);                                    //寫入資料}

值得一提的是路徑裡面的"%1”,即使去掉這個同樣可以進行關聯,但是在後面我們就會有一個很大的麻煩。我們在雙擊檔案時,是否會將路徑傳入應用程式就取決於這個參數,而且有一點要說明一下,上面函數的_RegKey.CreateSubKey(p_FileTypeName);
在vista下面執行的時候會報錯,因為許可權的原因。將vista的使用者控制關掉即可(在“使用者賬戶”中找到“開啟或關閉使用者賬戶控制”選項)。下面的一個函數是取消關聯

/// <summary>/// 取消檔案關聯/// </summary>/// <param name="p_FileTypeName">檔案類型</param>public static void DelReg(string p_FileTypeName){RegistryKey _Regkey = Registry.ClassesRoot.OpenSubKey("", true);RegistryKey _VRPkey = _Regkey.OpenSubKey(p_FileTypeName);if (_VRPkey != null){_Regkey.DeleteSubKey(p_FileTypeName, true);}if (_VRPkey != null){_Regkey.DeleteSubKeyTree("Exec");}}

到現在為止,程式已經有了一個基本雛形,我們可以看一下

 

這樣,我們雙擊副檔名為.zxl的檔案時,就會運行剛剛所寫的這個程式。但是光只有這樣還是不夠的,我們需要的是開啟雙擊的檔案。其實很簡單,只要在main方法中加入參數就可以了

/// <summary>/// 應用程式的主進入點。/// </summary>[STAThread]static void Main(string [] Args){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(new f_reader(Args));}

    預設建winform程式時,main和form的建構函式是空的,我們加上了一個參數列表,這樣的話,我們在雙擊檔案時就會將檔案的路徑傳入程式,到這時,我們無論對檔案進行什麼操作都隨心所欲了。 這樣還差很多,很多軟體都支援拖放,可以把檔案直接拖到軟體上就開啟了。下面我們寫下面的代碼,我們需要建立Form的DragEnter和DragDrop事件:

private void f_reader_DragEnter(object sender, DragEventArgs e){if (e.Data.GetDataPresent(DataFormats.FileDrop)){e.Effect = DragDropEffects.Link;}else{e.Effect = DragDropEffects.None;}}private void f_reader_DragDrop(object sender, DragEventArgs e){lb_file.Items.Add(((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString());//這個地方得到的就是拖放的檔案路徑}

到現在我們的程式就基本完成了。有臨時想到了一個事情,雙擊多個檔案時只開啟一個程式執行個體,臨時從網上搜了一下(下面的代碼沒有經過實驗):

 
感謝,下面內容轉自:http://www.cnblogs.com/Fooo/archive/2008/09/25/1298455.html

防止程式運行多個執行個體的方法有多種,如:通過使用互斥量和進程名等.而我想要實現的是:在程式運行多個執行個體時啟用的是第一個執行個體,使其獲得焦點,並在最上層顯示.

主要用到兩個API 函數:

  • ShowWindowAsync 該函數設定由不同線程產生的視窗的顯示狀態。
  • SetForegroundWindow 該函數將建立指定視窗的線程設定到前台,並且啟用該視窗。鍵盤輸入轉向該視窗,並為使用者改各種可視的記號。系統給建立前台視窗的線程分配的許可權稍高於其他線程。

代碼如下:
引用以下命名空間:
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;
//*****************************************************
  static class Program
    {
        /// <summary>
        /// 該函數設定由不同線程產生的視窗的顯示狀態。
        /// </summary>
        /// <param name="hWnd">視窗控制代碼</param>
        /// <param name="cmdShow">指定視窗如何顯示。查看允許值列表,請查閱ShowWlndow函數的說明部分。</param>
        /// <returns>如果函數原來可見,傳回值為非零;如果函數原來被隱藏,傳回值為零。</returns>
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
        /// <summary>
        /// 該函數將建立指定視窗的線程設定到前台,並且啟用該視窗。鍵盤輸入轉向該視窗,並為使用者改各種可視的記號。系統給建立前台視窗的線程分配的許可權稍高於其他線程。
        /// </summary>
        /// <param name="hWnd">將被啟用並被調入前台的視窗控制代碼。</param>
        /// <returns>如果視窗設入了前台,傳回值為非零;如果視窗未被設入前台,傳回值為零。</returns>
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        private const int WS_SHOWNORMAL = 1;

        /// <summary>
        /// 應用程式的主進入點。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Process instance = RunningInstance();
            if (instance == null)
            {
                Form1 frm = new Form1();
                Application.Run(new Form1());
            }
            else
            {
                HandleRunningInstance(instance);
            }

        }
        /// <summary>
        /// 擷取正在啟動並執行執行個體,沒有啟動並執行執行個體返回null;
        /// </summary>
        public static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            foreach (Process process in processes)
            {
                if (process.Id != current.Id)
                {
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
                    {
                        return process;
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 顯示已啟動並執行程式。
        /// </summary>
        public static void HandleRunningInstance(Process instance)
        {
            ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL); //顯示,可以注釋掉
            SetForegroundWindow(instance.MainWindowHandle);            //放到前端
        }
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.