我想在Quicker里创建一个接受拖放的窗口,用于快速处理文件。由于Quicker运行在高权限态,普通窗口无法接受拖放。
我尝试创建一个低权限的Winform窗口用来接受拖放文件,但是Winform需要STA线程来允许拖放。能否允许低权限模式也通过其他线程方式运行?
示例:
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Windows.Forms;
public class MainForm : Form
{
public ListBox listBoxFiles;
public List<string> listFiles = new List<string>();
public MainForm()
{
Text = "请将文件拖入此窗口";
Size = new System.Drawing.Size(500, 300);
listBoxFiles = new ListBox { Dock = DockStyle.Fill };
Controls.Add(listBoxFiles);
AllowDrop = true;
DragEnter += MainForm_DragEnter;
DragDrop += MainForm_DragDrop;
}
private void MainForm_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void MainForm_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
if (files != null && files.Length > 0)
{
listBoxFiles.Items.Clear();
listFiles.Clear();
foreach (string file in files)
{
listBoxFiles.Items.Add(file);
listFiles.Add(file);
}
}
}
}
public static string Exec(string paramValue)
{
using(MainForm f = new MainForm()){
f.ShowDialog();
return string.Join("\n",f.listFiles);
};
}
直接运行会提示
System.InvalidOperationException: DragDrop 注册失败。 System.Threading.ThreadStateException: 在可以调用 OLE 之前,必须将当前线程设置为单线程单元(STA)模式。请确保您的 Main 函数带有 STAThreadAttribute 标记。 在 System.Windows.Forms.Control.SetAcceptDrops(Boolean accept) --- 内部异常堆栈跟踪的结尾 --- 在 System.Windows.Forms.Control.SetAcceptDrops(Boolean accept) 在 System.Windows.Forms.Control.OnHandleCreated(EventArgs e) 在 System.Windows.Forms.Form.OnHandleCreated(EventArgs e) 在 System.Windows.Forms.Control.WmCreate(Message& m) 在 System.Windows.Forms.Control.WndProc(Message& m) 在 System.Windows.Forms.Form.WmCreate(Message& m) 在 System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)