使用pywin32在Windows桌面上获取所选文件

时间:2016-04-15 19:07:40

标签: python pywin32

我能够从资源管理器窗口中获取所有选定的文件,但我无法找到一种方法来获取桌面上的文件。

对于资源管理器窗口我有:

import win32com.client

def selected_files(): 
    clsid='{9BA05972-F6A8-11CF-A442-00A0C90A8F39}'
    ShellWindows=win32com.client.Dispatch(clsid)
    files = []
    for i in range(ShellWindows.Count):
        for j in range(ShellWindows[i].Document.SelectedItems().Count):
            files.append(ShellWindows[i].Document.SelectedItems().Item(j).Path)

    return files

我确实在c ++中有一些代码解决了这个问题,但是我想在python中完成它,任何人都可以帮我翻译它或者在python中找到另一种方法吗?

CComQIPtr<IWebBrowser2> AttachDesktopShellWindow()
{
    if(FAILED(CoInitialize(NULL)))
        MyPrintDebugError("Unable to initialize COM", GetLastError());

    CComQIPtr<IWebBrowser2> pWebBrowser2;
    CComPtr<IShellWindows> psw;
    psw.CoCreateInstance(CLSID_ShellWindows);
    if(!psw) return pWebBrowser2;

    VARIANT varEmpty = {VT_EMPTY};
    long handle;
    psw->FindWindowSW(&varEmpty, &varEmpty , SWC_DESKTOP, &handle, SWFO_NEEDDISPATCH, (IDispatch**)&pWebBrowser2);

    return pWebBrowser2;
}

vector<string> COMManager::GetItemsFromCOM(CComQIPtr<IWebBrowser2>  pWebBrowser2)
{
    vector<string> items;

    if (!pWebBrowser2)
    return items;

    CComQIPtr<IServiceProvider> psp(pWebBrowser2);
    CComPtr<IShellBrowser>      psb;
    CComPtr<IShellView>         psv;
    CComPtr<IFolderView>        pfv;
    CComPtr<IPersistFolder2>    ppf2;

    if(!psp) return items;
    psp->QueryService(SID_STopLevelBrowser,IID_IShellBrowser,(LPVOID*)&psb);

    if(!psb) return items;
    psb->QueryActiveShellView(&psv);

    if(!psv) return items;

    if (FAILED(psv->QueryInterface(IID_IFolderView,(void**)&pfv)))  return items;
    if (FAILED(pfv->GetFolder(IID_IPersistFolder2, (void**)&ppf2))) return items;
    LPITEMIDLIST pidlFolder;
    if (SUCCEEDED(ppf2->GetCurFolder(&pidlFolder)))
    {
        CComPtr<IDataObject> dao;
        if(SUCCEEDED(psv->GetItemObject(SVGIO_SELECTION,IID_IDataObject ,(void**)&dao)))
           items = vectorFromDataObject(dao);

        CoTaskMemFree(pidlFolder);
    }

    return items;
}

0 个答案:

没有答案