You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WinForm应用中实现任务栏右键显示「Recent Items」

实现Windows Form应用任务栏右键显示「Recent Items」的方法

Windows任务栏的「Recent Items」依赖系统的Jump List机制实现,在Visual Studio开发WinForm应用时,可通过以下步骤完成功能开发:

1. 添加必要引用与命名空间

首先需要引用System.Windows.Shell程序集,然后在代码中导入对应命名空间:

using System.Windows.Shell;

2. 初始化Jump List配置

在窗体的Load事件或构造函数中,开启最近项类别并注册相关事件:

private void MainForm_Load(object sender, EventArgs e)
{
    // 获取或创建当前应用的Jump List实例
    JumpList jumpList = JumpList.GetJumpList(Application.Current) ?? new JumpList();
    JumpList.SetJumpList(Application.Current, jumpList);

    // 启用最近项显示
    jumpList.ShowRecentCategory = true;

    // 注册事件处理项被拒绝或用户移除的情况
    jumpList.JumpItemsRejected += OnJumpItemsRejected;
    jumpList.JumpItemsRemovedByUser += OnJumpItemsRemoved;
}

private void OnJumpItemsRejected(object sender, JumpItemsRejectedEventArgs e)
{
    // 可在此添加日志记录或错误处理逻辑
}

private void OnJumpItemsRemoved(object sender, JumpItemsRemovedEventArgs e)
{
    // 可在此同步本地的最近项记录
}

3. 向最近项列表添加内容

当用户在应用中打开/创建文件后,调用以下方法将文件路径添加到Jump List:

private void AddFileToRecent(string filePath)
{
    if (!File.Exists(filePath)) return;

    JumpListItem item = JumpListItem.CreateJumpItemForFile(filePath);
    JumpList jumpList = JumpList.GetJumpList(Application.Current);
    
    if (jumpList != null)
    {
        jumpList.JumpItems.Add(item);
        jumpList.Apply();
    }
}

4. 处理最近项的打开请求

用户点击任务栏最近项时,Windows会通过命令行参数传递文件路径,需要在Program.cs中处理启动参数:

static class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        MainForm mainForm = new MainForm();

        // 处理启动参数(点击最近项打开文件的场景)
        if (args.Length > 0)
        {
            string targetFile = args[0];
            mainForm.OpenTargetFile(targetFile); // 调用窗体中自定义的打开文件方法
        }

        Application.Run(mainForm);
    }
}

注意事项

  • 测试时需先将应用固定到任务栏,操作几个文件后右键任务栏图标即可看到最近项;
  • 若应用需关联特定文件类型,需在项目中配置文件关联,确保Windows能正确传递启动参数;
  • 可通过JumpList.RecentCategoryName属性自定义最近项的类别名称。

内容的提问来源于stack exchange,提问作者puiuz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 06:10:58