对CEdit类进行继承,新类CDropFileEdit支持文件的拖拽得到文件名。使用的时候添加头文件到具体程序中,再使用类向导与资源文件关联起来就可以使用。具体代码如下
DropFileEdit.h
- #if
!defined(AFX_DROPFILEEDIT_H__412BC2B6_D7BF_4CBE_9EFB_FCC77B59A21F__INCLUDED_)
- #define
AFX_DROPFILEEDIT_H__412BC2B6_D7BF_4CBE_9EFB_FCC77B59A21F__INCLUDED_ - #if _MSC_VER > 1000
- #pragma once
- #endif // _MSC_VER > 1000
- // DropFileEdit.h : header file
- //
- /////////////////////////////////////////////////////////////////////////////
- // CDropFileEdit window
- class
CDropFileEdit :
public
CEdit - {
- // Construction
- public
: - CDropFileEdit();
- // Attributes
- public
: - // Operations
- public
: - // Overrides
-
// ClassWizard generated
virtual function overrides -
//{{AFX_VIRTUAL(CDropFileEdit) -
//}}AFX_VIRTUAL - // Implementation
- public
: -
virtual
~CDropFileEdit(); -
// Generated message map
functions - protected
: -
//{{AFX_MSG(CDropFileEdit)
- afx_msg
void
OnDropFiles(
HDROP
hDropInfo);
//添加消息处理 -
//}}AFX_MSG - DECLARE_MESSAGE_MAP()
- };
- /////////////////////////////////////////////////////////////////////////////
- //{{AFX_INSERT_LOCATION}}
- // Microsoft Visual C++ will insert additional
declarations immediately before the previous line. - #endif //
!defined(AFX_DROPFILEEDIT_H__412BC2B6_D7BF_4CBE_9EFB_FCC77B59A21F__INCLUDED_)
DropFileEdit.cpp
- // DropFileEdit.cpp : implementation file
- //
- #include "stdafx.h"
- #include "DropFileEdit.h"
- #ifdef _DEBUG
- #define new DEBUG_NEW
- #undef THIS_FILE
- static
char
THIS_FILE[] = __FILE__; - #endif
- /////////////////////////////////////////////////////////////////////////////
- // CDropFileEdit
- CDropFileEdit::CDropFileEdit()
- {
- }
- CDropFileEdit::~CDropFileEdit()
- {
- }
- BEGIN_MESSAGE_MAP(CDropFileEdit, CEdit)
-
//{{AFX_MSG_MAP(CDropFileEdit) - ON_WM_DROPFILES()
//消息处理 -
//}}AFX_MSG_MAP - END_MESSAGE_MAP()
- /////////////////////////////////////////////////////////////////////////////
- // CDropFileEdit message handlers
- void
CDropFileEdit::OnDropFiles(
HDROP
hDropInfo) - {
-
// TODO: Add your message
handler code here and/or call default -
//取得被拖动文件的数目 -
int
DropCount=DragQueryFile(hDropInfo,-1,NULL,0); -
for
(
int
i=0;i<DropCount;i++) - {
-
int
NameSize=DragQueryFile(hDropInfo,i,NULL,0); -
HANDLE
hHeap=GetProcessHeap(); -
char
*pName=(
LPSTR
)HeapAlloc(hHeap,HEAP_ZERO_MEMORY,NameSize++); -
if
(pName==NULL) - {
- MessageBox(
"给文件名分配暂存空间时出错!"
,
"错误信息"
,MB_ICONERROR); -
return
; - }
-
//取得第i个拖动文件名所占字节数 - DragQueryFile(hDropInfo,i,pName,NameSize);
-
//把文件名拷贝到缓冲区 -
//
m_Dialog_List.AddString(pName); -
//文件名加入listbox中显示 -
this
->SetWindowText(pName); - HeapFree(hHeap,HEAP_ZERO_MEMORY,pName);
-
//释放缓冲区 - }
- CEdit::OnDropFiles(hDropInfo);
- }