LoginSignup
4
5

More than 5 years have passed since last update.

WPFアプリからファイルをドラッグ

Posted at

WPFアプリからファイルをドラッグ

WPFアプリにドロップされた場合の例は結構あるんですが、WPFアプリからデスクトップやエクスプローラなんかにドラッグする時のサンプルが見つけ難かったので備忘録。

画面に表示されているコントロールを右クリックするとドラッグ開始です。

<Window x:Class="WpfApp6Drag.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp6Drag"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="500">
    <Window.Resources>
        <ResourceDictionary>
            <BitmapImage x:Key="neko" UriSource="Images/neko.jpg"/>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <Image Name="ImageWork" Source="{StaticResource neko}" Height="300" MouseDown="Image_MouseDown"/>
    </Grid>
</Window>
private void Image_MouseDown(object sender, MouseButtonEventArgs e)
{
    if (e.LeftButton == MouseButtonState.Pressed) {
        // 元の画像はとりあえずリソースから取得
        var img = FindResource("neko") as BitmapImage;

        // テンプラリフォルダに画像ファイル作成
        var filePath = System.IO.Path.GetTempPath() + "image.jpg";
        using (var fs = new FileStream(filePath, FileMode.Create)) {
            BitmapEncoder enc = new JpegBitmapEncoder();
            enc.Frames.Add(BitmapFrame.Create(img));
            enc.Save(fs);
        }

        // ドラッグ開始
        var dataObject = new DataObject(DataFormats.FileDrop, new[] { filePath });
        DragDrop.DoDragDrop(ImageWork, dataObject, DragDropEffects.Copy);
    }
}

文字列や画像イメージではなく、ファイルとしてドラッグさせたかったのでテンポラリフォルダにimage.jpgを一度作って、それをドラッグするようにしています。
ドラッグ自体は DragDrop.DoDragDrop()を呼べば後は勝手にやってくれるので簡単なんですが、ここに辿り着くまでが大変でした。

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5