C#Windows窗体:将图片放入WPF RichTextBox(在ElementHost中)

本文关键字:RichTextBox ElementHost WPF 窗体 C#Windows | 更新日期: 2023-09-27 18:23:45

我有一个c#Windows窗体项目,该项目在窗体上有一个WPF RichTextBox(在ElementHost中),并且想要拖动&将图片从资源管理器(Windows 7 x64)拖放到其中,但光标只显示不允许的符号。这是我的代码:

    private void Form1_Load(object sender, EventArgs e)
    {
        this.AllowDrop = true;
        elementHost1.AllowDrop = true;
    }
    public UserControl1()
    {
        InitializeComponent();
        Background = System.Windows.Media.Brushes.Transparent;
        this.AllowDrop = true;
        richTextBox1.AllowDrop = true;
    }

使用设计器订阅事件。他们都没有被解雇:

    private void richTextBox1_DragEnter(object sender, DragEventArgs e)
    {
        MessageBox.Show("Test");
    }
    private void richTextBox1_DragLeave(object sender, DragEventArgs e)
    {
        MessageBox.Show("Test");
    }
    private void richTextBox1_DragOver(object sender, DragEventArgs e)
    {
        MessageBox.Show("Test");
    }
    private void richTextBox1_Drop(object sender, DragEventArgs e)
    {
        MessageBox.Show("Test");
    }

如果我使用Windows窗体RichTextBox是可行的,但我需要一个WPF RichTextBox:

    private void Form1_Load(object sender, EventArgs e)
    {
        richTextBox1.AllowDrop = true;
        richTextBox1.DragDrop += new DragEventHandler(richTextBox1_DragDrop);
    }
    private void richTextBox1_DragDrop(object sender, EventArgs e)
    {
        MessageBox.Show("Test");
    }

C#Windows窗体:将图片放入WPF RichTextBox(在ElementHost中)

您需要使用PreviewDragEnterPreviewDragOverPreviewDrop事件:

    public Window1()
    {
        InitializeComponent();
        // mainRTB is the name of my RichTextBox.
        mainRTB.PreviewDragEnter += new DragEventHandler(mainRTB_PreviewDragEnter);
        mainRTB.PreviewDragOver += new DragEventHandler(mainRTB_PreviewDragEnter);
        mainRTB.PreviewDrop += new DragEventHandler(mainRTB_PreviewDrop);
        mainRTB.AllowDrop = true;
    }
    static bool IsImageFile(string fileName)
    {
        return true;  // REPLACE THIS STUB WITH A REAL METHOD.
    }
    void mainRTB_PreviewDrop(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(DataFormats.FileDrop))
        {
            // Note that you can have more than one file.
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            if (files != null && files.Length > 0)
            {
                // Filter out non-image files
                if (mainRTB.Document.PasteImageFiles(mainRTB.Selection, files.Where(IsImageFile)))
                    e.Handled = true;
            }
        }
    }
    void mainRTB_PreviewDragEnter(object sender, DragEventArgs e)
    {
        string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
        // Filter out non-image files
        if (files != null && files.Length > 0 && files.Where(IsImageFile).Any())
        {
            // Consider using DragEventArgs.GetPosition() to reposition the caret.
            e.Handled = true;
        }
    }

然后以下方法在当前选择范围内粘贴图像:

    public static bool PasteImageFiles(this FlowDocument doc, TextRange selection, IEnumerable<string> files)
    {
        // Assuming you have one file that you care about, pass it off to whatever
        // handling code you have defined.
        FlowDocument tempDoc = new FlowDocument();
        Paragraph par = new Paragraph();
        tempDoc.Blocks.Add(par);
        foreach (var file in files)
        {
            try
            {
                BitmapImage bitmap = new BitmapImage(new Uri(file));
                Image image = new Image();
                image.Source = bitmap;
                image.Stretch = Stretch.None;
                InlineUIContainer container = new InlineUIContainer(image);
                par.Inlines.Add(container);
            }
            catch (Exception)
            {
                Debug.WriteLine("'"file'" was not an image");
            }
        }
        if (par.Inlines.Count < 1)
            return false;
        try
        {
            var imageRange = new TextRange(par.Inlines.FirstInline.ContentStart, par.Inlines.LastInline.ContentEnd);
            using (var ms = new MemoryStream())
            {
                string format = DataFormats.XamlPackage;
                imageRange.Save(ms, format, true);
                ms.Seek(0, SeekOrigin.Begin);
                selection.Load(ms, format);
                return true;
            }
        }
        catch (Exception)
        {
            Debug.WriteLine("Not an image");
            return false;
        }
    }
}

顺便说一句,这种方法避免了使用剪贴板将图像粘贴到RichTextBox中——有时会看到这样做,但并不理想。

您可能希望将图像放置在当前放置位置,而不是粘贴到当前所选内容上。如果是这样,请从以下内容开始:在拖放过程中获取鼠标位置:如何在运行时将图像插入WPF RichTextBox中的文本之间,使文本在图像周围浮动