Каждый раз, когда я сохраняю определенный файл сценария, с которым я работаю в NotePad ++, мне необходимо загрузить изменения на наш сервер, чтобы мы могли развернуть изменения на разных машинах.Ключи для событий Windows для сохранения файлов
Иногда я забыл загрузить изменения после рефакторинга моего кода в NotePad ++, и мне было интересно, есть ли способ создать простое приложение, которое будет прослушивать событие «Сохранить» и автоматически загружать файл для меня.
В настоящее время я работаю на ОС Windows и надеялся сделать это с помощью C++. Я хотел бы изучить Windows Events и, возможно, привязать к событию, чтобы выполнить это. Любые другие языки также приветствуются.
Любые идеи или советы?
Вот мой код до сих пор в соответствии с рекомендациями Джоша ниже:
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <tchar.h>
void RefreshDirectory(LPTSTR);
void WatchDirectory(LPTSTR);
void _tmain(int argc, TCHAR *argv[])
{
if (argc != 2)
{
_tprintf(TEXT("Usage: %s <dir>\n"), argv[0]);
return;
}
WatchDirectory(argv[1]);
}
void WatchDirectory(LPTSTR lpDir)
{
DWORD dwWaitStatus;
HANDLE dwChangeHandles[2];
TCHAR lpDrive[4];
TCHAR lpFile[_MAX_FNAME];
TCHAR lpExt[_MAX_EXT];
_tsplitpath_s(lpDir, lpDrive, 4, NULL, 0, lpFile, _MAX_FNAME, lpExt, _MAX_EXT);
lpDrive[2] = (TCHAR)'\\';
lpDrive[3] = (TCHAR)'\0';
// Watch the directory for file creation and deletion.
dwChangeHandles[0] = FindFirstChangeNotification(
lpDir, // directory to watch
FALSE, // do not watch subtree
FILE_NOTIFY_CHANGE_LAST_WRITE); // watch file name changes
if (dwChangeHandles[0] == INVALID_HANDLE_VALUE)
{
printf("\n ERROR: FindFirstChangeNotification function failed.\n");
ExitProcess(GetLastError());
}
// Make a final validation check on our handles.
if ((dwChangeHandles[0] == NULL))
{
printf("\n ERROR: Unexpected NULL from FindFirstChangeNotification.\n");
ExitProcess(GetLastError());
}
// Change notification is set. Now wait on both notification
// handles and refresh accordingly.
while (TRUE)
{
// Wait for notification.
printf("\nWaiting for notification...\n");
// Waits until the specified object is in the signaled state or
// the time-out interval elapses.
// Because our second parameter is set to INFINITE, the function will
// return only when the object is signaled.
dwWaitStatus = WaitForSingleObject(dwChangeHandles, INFINITE);
switch (dwWaitStatus)
{
// Our return value, WAIT_OBJECT_0 signifies that the first object
// signaled the event.
case WAIT_OBJECT_0:
// A file was created, renamed, or deleted in the directory.
// Refresh this directory and restart the notification.
RefreshDirectory(lpDir);
if (FindNextChangeNotification(dwChangeHandles[0]) == FALSE)
{
printf("\n ERROR: FindNextChangeNotification function failed.\n");
ExitProcess(GetLastError());
}
break;
case WAIT_TIMEOUT:
// A timeout occurred, this would happen if some value other
// than INFINITE is used in the Wait call and no changes occur.
// In a single-threaded environment you might not want an
// INFINITE wait.
printf("\nNo changes in the timeout period.\n");
break;
default:
printf("\n ERROR: Unhandled dwWaitStatus.\n");
ExitProcess(GetLastError());
break;
}
}
}
void RefreshDirectory(LPTSTR lpDir)
{
// This is where you might place code to refresh your
// directory listing, but not the subtree because it
// would not be necessary.
_tprintf(TEXT("Directory (%s) changed.\n"), lpDir);
}
Эй @Josh, я использую этот метод до сих пор, и это работает отлично! Используя FindFirstChangeNotification, я смог обнаружить последний раз, когда файл был изменен. Мне было интересно, можете ли вы предоставить мне некоторые разъяснения о том, как точно использовать функцию ReadDirectoryChanges. Поиск различных статей в Интернете оказался бесполезным. До сих пор я написал свой код в своем оригинальном сообщении. Еще раз спасибо! –