一日一コード 28.つまったら他のネタで。

DirectDrawのメッセージループ回り、半透明合成とかフェードアウトとか時間効果のための処理があまり進まないので、.net でドラッグアンドドロップ対応してみた。


楽と言えば楽だけど。自力で探してたら時間かかりすぎる。

なんじゃこりゃ。(99% MSDNよりコピペ)


public int InitalizeComponent()
{
try
{
this.picture = new Bitmap("sample.bmp");
this.ClientSize = picture.Size; //リサイズ
this.BackgroundImage = this.picture;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

this.AllowDrop = true;
this.DragDrop += new DragEventHandler( this.MainForm_DragDrop );
this.DragEnter += new DragEventHandler( this.MainForm_DragEnter );
return 0;
}

void MainForm_DragEnter(object sender, DragEventArgs e)
{
// If the data is a file or a bitmap, display the copy cursor.
if (e.Data.GetDataPresent(DataFormats.Bitmap) ||
e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}

private void MainForm_DragDrop(object sender, DragEventArgs e)
{
// Handle FileDrop data.
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
// Assign the file names to a string array, in
// case the user has selected multiple files.
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
try
{
// Assign the first image to the picture variable.
this.picture = Image.FromFile(files[0]);
// Set the picture location equal to the drop point.
this.pictureLocation = this.PointToClient(new Point(e.X, e.Y));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}

// Handle Bitmap data.
if (e.Data.GetDataPresent(DataFormats.Bitmap))
{
try
{
// Create an Image and assign it to the picture variable.
this.picture = (Image)e.Data.GetData(DataFormats.Bitmap);
// Set the picture location equal to the drop point.
this.pictureLocation = this.PointToClient(new Point(e.X, e.Y));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
// Force the form to be redrawn with the image.
this.BackgroundImage = this.picture;
this.ClientSize = this.picture.Size;
this.Invalidate();
}

private Image picture;
private Point pictureLoca