|
发表于 2024-10-12 10:48:57
|
显示全部楼层
要在C++ MFC中实现文件夹监听,并将新增的特定类型文件名加入ListBox控件,可以使用Windows的文件系统改动通知功能。以下是一个基本的实现思路:
1. **创建MFC对话框应用**:
- 使用MFC应用程序向导创建一个基于对话框的应用程序。
- 在对话框上添加一个ListBox控件。
2. **使用`FindFirstChangeNotification`等API来监控文件夹**:
- 使用`FindFirstChangeNotification`函数来注册文件夹变更通知。
- 使用一个工作线程不断地调用`WaitForSingleObject`来等待文件夹的变化事件发生。
3. **响应文件夹变化**:
- 在检测到文件夹内容变化时,使用`CFileFind`类查找新增的特定类型文件。
- 将检测到的文件名添加到ListBox控件。
下面是一个简单的代码示例,用于展示基本实现:
- #include <afxwin.h>
- #include <afxdlgs.h>
- #include <afxcmn.h>
- #include <thread>
- #include <atomic>
- #include <string>
- class CMyDialog : public CDialogEx {
- public:
- CListBox m_listBox;
- std::atomic<bool> m_running;
- CMyDialog() : CDialogEx(IDD_MYDIALOG), m_running(true) { }
- BOOL OnInitDialog() override {
- CDialogEx::OnInitDialog();
- m_listBox.SubclassDlgItem(IDC_LIST1, this);
- std::thread([this] {
- WatchDirectory();
- }).detach();
- return TRUE;
- }
- void WatchDirectory() {
- CString folderPath = _T("C:\\YourDirectory");
- HANDLE hChange = FindFirstChangeNotification(
- folderPath, FALSE, FILE_NOTIFY_CHANGE_FILE_NAME);
- if (hChange == INVALID_HANDLE_VALUE) return;
- while (m_running) {
- DWORD waitStatus = WaitForSingleObject(hChange, INFINITE);
- if (waitStatus == WAIT_OBJECT_0) {
- HandleDirectoryChange(folderPath);
- FindNextChangeNotification(hChange);
- }
- }
- FindCloseChangeNotification(hChange);
- }
- void HandleDirectoryChange(LPCTSTR lpPath) {
- CFileFind finder;
- BOOL bWorking = finder.FindFile(std::wstring(lpPath) + _T("\\*.txt"));
- while (bWorking) {
- bWorking = finder.FindNextFile();
- if (!finder.IsDots() && !finder.IsDirectory()) {
- m_listBox.AddString(finder.GetFileName());
- }
- }
- }
- ~CMyDialog() {
- m_running = false;
- }
- };
- class CMyApp : public CWinApp {
- public:
- BOOL InitInstance() override {
- CMyDialog dlg;
- m_pMainWnd = &dlg;
- INT_PTR nResponse = dlg.DoModal();
- return FALSE;
- }
- };
- BEGIN_MESSAGE_MAP(CMyDialog, CDialogEx)
- END_MESSAGE_MAP()
- CMyApp theApp;
复制代码
### 注意事项:
- 确保替换`C:\\YourDirectory`和文件类型`*.txt`为你需要监听的路径和文件类型。
- `FindFirstChangeNotification`对文件夹的子目录不递归,需要自行处理。
- 代码中使用了简单的多线程,需考虑线程安全问题。
- 销毁对话框时,确保线程能正常退出,避免资源泄露。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|