create shortcut

本文介绍了一种使用C#在开始菜单中创建程序快捷方式的方法。通过.NET Framework提供的IWshRuntimeLibrary,可以轻松地在指定文件夹下创建.lnk文件,并指向目标程序路径。

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);

<script> import Launcher from './Launcher.vue'; import LauncherLite from './LauncherLite.vue'; import Settings from './Settings.vue'; import DragDropResource from './DragDropResource.vue'; import { invoke } from "@tauri-apps/api/core"; import { useToast } from "vue-toastification"; import { listen } from '@tauri-apps/api/event'; import { inject, onUnmounted as vueOnUnmounted } from 'vue'; import { ref, reactive, onMounted, nextTick } from 'vue'; const toast = useToast() export default { components: { Launcher, LauncherLite, Settings, DragDropResource }, setup() { const theme = inject('theme'); const launchers = ref([]); const editMode = ref(true); const showSetting = ref(false); const dragDropResourcePaths = ref([]); // 右键菜单相关状态 const showLauncherMenu = ref(false); const launcherMenuPositionTop = ref(0); const launcherMenuPositionLeft = ref(0); const selectedLauncherMenuLauncher = ref(null); // 全局点击事件,关闭右键菜单 const handleGlobalClick = (e) => { // 如果点击的不是右键菜单本身,则关闭菜单 if (!e.target.closest('.custom-contextmenu')) { showLauncherMenu.value = false; selectedLauncherMenuLauncher.value = null; } }; const setupEventListener = async () => { try { // 使用 await 确保监听器设置完成 const unlisten = await listen('launcher:drag_drop_resource', (event) => { if (dragDropResourcePaths.value.length == 0) { dragDropResourcePaths.value = Array.from(event.payload.paths); } }); // 保存取消监听的函数,以便在组件卸载时调用 const unlistenRef = ref(unlisten); document.addEventListener('click', handleGlobalClick); // 返回清理函数 return () => { if (unlistenRef.value) { unlistenRef.value(); } document.removeEventListener('click', handleGlobalClick); }; } catch (error) { console.error('Failed to setup event listener:', error); } }; const launch = async (launcherId) => { try { await invoke("launch", { launcherId: launcherId }); } catch (error) { console.error('Launch failed:', error); toast.error('启动失败'); } }; const createLauncher = async () => { try { // 修正拼写错误:craete_launcher → create_launcher await invoke("create_launcher"); editMode.value = true; await refreshLaunchers(); } catch (error) { console.error('Create launcher failed:', error); toast.error('创建启动器失败'); } }; const refreshLaunchers = async () => { try { const data = await invoke("query_launchers"); launchers.value = data || []; } catch (error) { console.error('Refresh launchers failed:', error); toast.error('刷新启动器列表失败'); launchers.value = []; } }; // type 0->左移,1-右移 const moveLauncher = async (launcherId, type) => { try { // 找到目标元素的索引 const ids = launchers.value.map(launcher => launcher.id); const index = ids.findIndex(id => id === launcherId); // 如果未找到目标元素,直接返回 if (index === -1) { return; } if (type === 0 && index > 0) { // 向左移动(交换与左边的元素) [ids[index], ids[index - 1]] = [ids[index - 1], ids[index]]; } else if (type === 1 && index < ids.length - 1) { // 向右移动(交换与右边的元素) [ids[index], ids[index + 1]] = [ids[index + 1], ids[index]]; } const sortList = ids.map((id, index) => ({ id: id, sort: index })); await invoke("modify_launcher_sort", { launchers: sortList }); await refreshLaunchers(); } catch (error) { console.error('Move launcher failed:', error); toast.error('移动启动器失败'); } }; const toggleEditMode = async () => { try { await invoke("save_setting", { key: "editMode", value: editMode.value ? "true" : "false" }); await fetchEditModeStatus(); } catch (error) { console.error('Toggle edit mode failed:', error); toast.error('切换编辑模式失败'); } }; // 获取当前编辑模式设置 const fetchEditModeStatus = async () => { try { const em = await invoke("read_setting", { key: "editMode" }); editMode.value = em == null || em.value === "true"; } catch (error) { console.error('Fetch edit mode status failed:', error); editMode.value = true; // 默认值 } }; const openSetting = async () => { showSetting.value = true; }; const closeSetting = async () => { showSetting.value = false; }; const cleanDragDropResourcePaths = async () => { dragDropResourcePaths.value.splice(0, dragDropResourcePaths.value.length); }; const confirmDragDrop = async () => { dragDropResourcePaths.value.splice(0, dragDropResourcePaths.value.length); await refreshLaunchers(); }; // 显示右键菜单 const toggleShowContextMenu = (launcherData, event) => { event.preventDefault(); event.stopPropagation(); // 设置菜单位置 launcherMenuPositionTop.value = event.clientY; launcherMenuPositionLeft.value = event.clientX; // 记录选中的launcher selectedLauncherMenuLauncher.value = launcherData; // 显示菜单 showLauncherMenu.value = true; }; // 右键菜单操作 const logLauncherName = () => { console.log("当前Launcher名称: ", selectedLauncherMenuLauncher.value?.name); showLauncherMenu.value = false; }; // 创建launcher快捷键 const createLauncherShortcut = async () => { try { let res = await invoke("create_handler_shortcut", { launcherId: selectedLauncherMenuLauncher.value.id }); showLauncherMenu.value = false; toast.success("快捷方式创建成功\r\n位置: " + res); } catch (error) { console.error('Create shortcut failed:', error); toast.error('创建快捷方式失败'); showLauncherMenu.value = false; } }; let cleanupEventListener = null; // 在组件挂载时初始化 onMounted(async () => { try { cleanupEventListener = await setupEventListener(); await fetchEditModeStatus(); await refreshLaunchers(); } catch (error) { console.error('Component mount initialization failed:', error); } }); // 清理全局事件监听 vueOnUnmounted(() => { if (cleanupEventListener) { cleanupEventListener(); } document.removeEventListener('click', handleGlobalClick); }); return { theme, launchers, editMode, showSetting, dragDropResourcePaths, showLauncherMenu, launcherMenuPositionTop, launcherMenuPositionLeft, selectedLauncherMenuLauncher, launch, createLauncher, refreshLaunchers, moveLauncher, toggleEditMode, openSetting, closeSetting, cleanDragDropResourcePaths, confirmDragDrop, toggleShowContextMenu, logLauncherName, createLauncherShortcut }; } }; </script>给我完整代码
最新发布
08-31
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值