记录一些经验

学习,生活

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Searching the Source Code of Adding my Program Shortcut into Start Menu

Now, I am searching the source code by C# of adding my program shortcut into Start Menu. I think its solution maybe is to modify the correct key in the registry. And I have acquired knowledge about the the class library “Microsoft.Win32” which includes some methods to handle the registry. I believe I can find the perfect sollution at last! :) Maybe.

Oops... now,  I haven't get some information correlative with this issue. So, if somebody else will tell me the answer directly, even give me some source code, It is very nice! I will appreciate his or her help:) 

/*Modified on October 03,2004*/

-------*******************************************************-------------------------------

ps: OK! I have found the answer already! It's great and very simple. But it make me embarrassed what I guessed before was definitely wrong. We need not handle the registry, in fact, there are some convenient methods in .Net.

There is solution as bellow:

using IWshRuntimeLibrary;

//folderType is special system folder type;
//linkName is shortcut's title which you want to add;
public bool AddShortCut(Environment.SpecialFolder folderType,string targetDir,string linkName)
{
       try
       {
             string folder = Environment.GetFolderPath(folderType) + "\\" + linkName;
             // Create a Windows Script Host Shell class
             IWshShell_Class shell = new IWshShell_ClassClass();
            // Define the shortcut file
            IWshShortcut_Class shortcut = shell.CreateShortcut(folder + ".lnk") as IWshShortcut_Class;
            shortcut.TargetPath = targetDir;
            shortcut.Save();   
            return true; 
       }
       catch (Exception ex)
       {
               return false;
        }     
}

If you want to add the shortcut to StartMenu's Program menu, you can invoke the AddShortCut() method like this:

AddShortCut(Environment.SpecialFolder.Programs);

Environment.SpecialFolder is enum type, it includes serveral special system folder type, for example, Startup Menu, DesktopDirectory, and or so.

Of course, in order to use CreateShortcut method of IWshShell_Class, at first you should add reference to your project, and select “Windows Script Host Object Mode” from “Add Reference” Dialog Box in “Com” tab. Then add it into your project. So assembly IWshRuntimeLibrary would be listed in your Solution.

-------*******************************************************-------------------------------

posted on 2008-03-17 09:10  将飞  阅读(408)  评论(0)    收藏  举报