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

如何在通过Process.Start打开的文件夹搜索框中粘贴文本

打开文件夹后自动在搜索框填入指定文本的实现方案

因为Process.Start(@"C:\temp")只能启动文件夹进程,无法直接操控窗口控件,你需要借助Windows API来定位搜索框并填入文本,以下是C#的具体实现:

核心思路

通过Windows API查找文件夹窗口、定位搜索框控件,激活窗口后向搜索框发送文本消息。

1. 声明所需Windows API函数

先在代码中引入必要的系统API:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

public class FolderSearchHandler
{
    [DllImport("user32.dll", SetLastError = true)]
    private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    [DllImport("user32.dll", SetLastError = true)]
    private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

    [DllImport("user32.dll")]
    private static extern bool SetForegroundWindow(IntPtr hWnd);

    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, string lParam);

    private const uint WM_SETTEXT = 0x000C;
}

2. 实现打开文件夹并填充搜索框的方法

添加方法处理窗口查找和文本输入逻辑:

public static void LaunchFolderAndSearch(string folderPath, string searchContent)
{
    // 启动目标文件夹
    Process.Start(folderPath);
    // 等待窗口加载完成,可根据系统性能调整等待时长
    Thread.Sleep(1000);

    // 获取文件夹窗口句柄,优先通过文件夹名称匹配
    string folderName = System.IO.Path.GetFileName(folderPath);
    IntPtr folderWindow = FindWindow("CabinetWClass", folderName);
    
    // 若按名称找不到,尝试匹配文件夹窗口类名(忽略标题)
    if (folderWindow == IntPtr.Zero)
    {
        folderWindow = FindWindow("CabinetWClass", null);
    }

    if (folderWindow != IntPtr.Zero)
    {
        // 激活文件夹窗口
        SetForegroundWindow(folderWindow);
        
        // 逐层定位搜索框控件(适配Windows默认文件管理器结构)
        IntPtr toolbarContainer = FindWindowEx(folderWindow, IntPtr.Zero, "WorkerW", null);
        toolbarContainer = FindWindowEx(toolbarContainer, IntPtr.Zero, "ReBarWindow32", null);
        toolbarContainer = FindWindowEx(toolbarContainer, IntPtr.Zero, "SearchBox", null);
        IntPtr searchInputBox = FindWindowEx(toolbarContainer, IntPtr.Zero, "Edit", null);

        if (searchInputBox != IntPtr.Zero)
        {
            // 向搜索框发送指定文本
            SendMessage(searchInputBox, WM_SETTEXT, IntPtr.Zero, searchContent);
        }
    }
}

3. 调用示例

在主程序中直接调用方法即可:

FolderSearchHandler.LaunchFolderAndSearch(@"C:\temp", "你要搜索的文本");

注意事项

  • Thread.Sleep(1000)的等待时间可能需要调整,确保窗口完全加载后再执行后续操作。
  • 不同Windows版本的文件管理器控件层级可能有细微差异,如果控件查找失败,可以用**Spy++**工具查看实际的控件类名和层级结构。
  • 该方案仅适用于Windows系统,依赖Windows原生API。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 21:35:13