Drag & Drop 기능 구현하기
Form을 하나 생성하고, Mouse Drag&Drop하면 해당 이미지를 출력하는 기능
의외로 싶당.. 역쉬--C#이다..
1. 먼저..
form을 하나 만들고, 하기처럼 AllowDropo을 선언하자.
public ScreenForm()
{
InitializeComponent();
// drag and drop 되도록 allow drop 설정
this.AllowDrop = true;
}
2. 이벤트에서 DragDrop/ DragEnter 2개를 추가한다.
3. 추가된 이벤트에 하기 코드넣으면 끝..
private void ScreenForm_DragDrop(object sender, DragEventArgs e)
{
// 이미지 파일을 끌어다 놨을때 할 동작을 정해준다.
try
{
// 가져온 파일의 경로를 알자
var dirName = (string[])e.Data.GetData(DataFormats.FileDrop);
// 알아낸 경로를 이용하여 이미지 파일이 아니면 loading하지 않는다.
// 여러 파일 중 하나만 읽어서 출력하는 것으로 함.
this.BackgroundImage = Image.FromFile(dirName[0], true);
// 경로 중에 파일명만 잘라서 메시지박스로 표시하여 무엇을 읽었는지 알려준다.
String szbuf = string.Empty;
szbuf = dirName[0].Substring(dirName[0].LastIndexOf(@"/") + 1);
MessageBox.Show("Loading File Name : " + szbuf);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
// + 표시가 되도록 효과를 넣는다.
private void ScreenForm_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.Data.GetDataPresent(DataFormats.FileDrop) ?
DragDropEffects.Copy : DragDropEffects.None;
}
이상.