electron中拖动文件到桌面案例

发布时间:2026/7/9 3:55:03

electron中拖动文件到桌面案例 效果图main.jsconstpathrequire(node:path);const{app,BrowserWindow,ipcMain,nativeImage}require(electron);constSAFE_FILES[file1.txt];functioncreateWindow(){constwinnewBrowserWindow({width:800,height:600,title:File Drag Demo,webPreferences:{preload:path.join(__dirname,preload.js),contextIsolation:true,nodeIntegration:false,},});win.loadFile(index.html);}app.whenReady().then((){ipcMain.on(get-draggable-files-sync,(event){event.returnValueSAFE_FILES.map((name)({name,path:path.resolve(__dirname,name),}));});ipcMain.on(start-file-drag-sync,(event,filePath){constallowedPathsnewSet(SAFE_FILES.map((name)path.resolve(__dirname,name)));consttargetPathpath.resolve(filePath);event.returnValuefalse;if(!allowedPaths.has(targetPath)){return;}consticonPathpath.join(__dirname,drag-icon.png);constdragIconnativeImage.createFromPath(iconPath);if(dragIcon.isEmpty()){console.error(Failed to decode drag icon:${iconPath});return;}try{event.sender.startDrag({file:targetPath,icon:dragIcon,});event.returnValuetrue;}catch(error){console.error(startDrag failed:,error);}});createWindow();app.on(activate,(){if(BrowserWindow.getAllWindows().length0){createWindow();}});});app.on(window-all-closed,(){if(process.platform!darwin){app.quit();}});preload.jsconst{contextBridge,ipcRenderer}require(electron);contextBridge.exposeInMainWorld(fileDrag,{list(){returnipcRenderer.sendSync(get-draggable-files-sync);},start(filePath){returnipcRenderer.sendSync(start-file-drag-sync,filePath);},});renderer.jsconstfileListdocument.querySelector(#fileList);constfileswindow.fileDrag.list();for(constfileEntryoffiles){constitemdocument.createElement(div);item.classNamefile-item;item.draggabletrue;item.textContentfileEntry.name;item.addEventListener(dragstart,(event){constokwindow.fileDrag.start(fileEntry.path);if(!ok){event.preventDefault();console.error(Drag rejected for${fileEntry.name});}});fileList.append(item);}index.html!doctypehtmlhtmllangzh-CNheadmetacharsetUTF-8/metanameviewportcontentwidthdevice-width, initial-scale1.0/titleElectron 文件拖拽 Demo/titlelinkrelstylesheethref./styles.css//headbodymainclassapph1拖文件到桌面/h1p按住下面任意文件直接拖到桌面或文件夹里。/psectionclassfile-listidfileList/section/mainscriptsrc./renderer.js/script/body/htmlstyle.css:root{color-scheme:light dark;font-family:Arial,Microsoft YaHei,sans-serif;}*{box-sizing:border-box;}body{margin:0;}.app{max-width:420px;margin:48px auto;padding:0 24px;}h1{margin:0 0 8px;font-size:28px;}p{margin:0 0 24px;color:#666;}.file-list{display:grid;gap:12px;}.file-item{padding:16px 18px;border:1px solid #d6d6d6;border-radius:12px;background:#f7f7f7;cursor:grab;user-select:none;}.file-item:active{cursor:grabbing;}media(prefers-color-scheme:dark){body{background:#202124;color:white;}p{color:#bdbdbd;}.file-item{border-color:#555;background:#2b2c2f;}}media(prefers-color-scheme:light){body{background:#fff;color:black;}}

相关新闻