Подскажите пожалуйста пример кода,
чтобы запущенное приложение могло редактировать свои ресурсы.
Хочу в ресурсах хранить настройки приложения.
Не спрашивайте зачем, надо :)
Уважаемые авторы вопросов! Большая просьба сообщить о результатах решения проблемы на этой странице. Иначе, следящие за обсуждением, возможно имеющие аналогичные проблемы, не получают ясного представления об их решении. А авторы ответов не получают обратной связи. Что можно расценивать, как проявление неуважения к отвечающим от автора вопроса.
07-06-2006 12:00 | Комментарий к предыдущим ответам
07-06-2006 11:33 | Комментарий к предыдущим ответам
BTW, запущенный exe'шник нельзя открыть на запись... но его можно переименовать. Т. е. переименовываем .exe файл, создаём новый с таким же именем и содержимым старого, а вот в него уже спокойно пишем. Единственный минус в том, что останется старая версия exe'шника с другим именем... Тут уже могут быть варианты: если файл этот не очень мешает, то удалить его можно при следующем запуске. Или при выходе запустить самого себя ещё раз с каким-нить параметром, чтобы новый процесс, дождавшись завершения старого, удалил файл.
Python
1. экспериментальным путем выяснено: хэндл запущенного exe в системе WinXP SP2 в user-mode недоступен, как утверждают источники, в Win2K его можно найти.
2. даже если хэндл удастся найти, то он будет доступен только на чтение, придется изменять права доступа на него, это нетривиальная задача
Могу предложить дикий способ. Попробуй открыть новый файл, узнаешь его Handle. Windows, как показывает мой опыт, выделяет Handle довольно последовательно, поэтому есть шанс, что в диапазоне +/- скажем $1000 найдется хендл нашего файла. Для каждого хендла из этого диапазона пробуем получить его размер, если он совпадает с размером нашего файла, то вполне вероятно, что это "наш клиент". Пробуем прочитать какие-нибудь данные, если получится и мы прочитаем ожидаемые данные - то это точно "наш клиент" и мы используем WriteFile, чтобы записать необходимую информацию. Правда, что делать, если подходящий нендл не найден я не знаю.
Почитав разную инфу, я понял, что единственный способ писать в запущенный ехе - открывать диск и писать напрямую в кластеры, но работает это только под XP
Наиболее реальные варианты -
1) создание времменной проги, которая будет запускаться после завершения главной проги и ее редактировать
2) создание копии главной проги, ее редактирование ,создание bat, который удалит старую ,переименует новую
Не, зашибись, все работает... дописал ПР2 в конец первой, а первая открывает для чтения сама себя, переписывает последние m байт в другой файл(m-размер ПР2) и запускает. Все перезаписывается... долго правдо...
Я старые исходники посмотрел у меня там в одном файле несолько прог было, а моя только доставала из него нужную и запускала. А вот в нее саму скопировать я не пробовал, ибо эта идея - бредовая....
Сразу попрошу не кидать в меня кирпичами и не говорить, что я псих... Я так делал и это работало...
Если нужно просто изменять какую-то инфу в своем exe то можно сделать так:
В основной программе (ПР1) объявить константу типа '<111@@@!!!@@@> n символов полезной ифнормации', где "<111@@@!!!@@@>" - некий ключ, а "n символов полезной ифнормации" - соответственно n символов полезной ифнормации....
Далее написать программу(ПР2), которая :
1. открывает файл 'XXX.txt' в котором есть три строки: адрес ПР1, ключ-строка, n символов полезной ифнормации, которяю нужно переписать.
2. В цикле ждет момента когда сможет редактировать файл ПР1(т.е. пока ПР1 не закроется)
3. Открывает файл ПР1 и ищет ключ-строку, после чего заменяет n символов полезной ифнормации находящихся после нее.
4. Удаляет 'XXX.txt'
5. Создает ,батник, который удалит ее саму и самого себя
6. закрывается
После компиляции ПР2 открываем ее в текстовом редакторе и копируем все как константу в ПР1.
При завершении работы ПР1 она создает два файла:
'XXX.txt' - в который записывает свой адрес, ключ-строку и измененные данные,
и 'XXX.exe' - в который записывает константу(т.е. exe ПР2)
После чего запускает этот самый XXX.exe и закрывается.
ПР1 читает нужную инфу из константы с ключем...
Разумеетя, все эта фигня работает(если работает) только при наличии прав админа.
Я уже сказал, что это изврат, но иногда даже такая фигня может оказаться полезной...
мда. потратив час на поиски хэндла запущенного exe в системе пришел к выводу что найти его не удалось :-( ну ладно. тогда можно открыть девайс в RAW режиме и писать прямо в файл
SLoW:
Я так понял, это ресурсы изменяются в памяти,
а как потом это на диск сохранить?
Вот у Русиновича прожка handle.exe каким-то образом
закрывает хендл и потом можно удалять, изменять...
[i]
The LoadString function loads a string resource from the executable file associated with a specified module, copies the string into a buffer, and appends a terminating null character.
int LoadString(
HINSTANCE hInstance, // handle of module containing string resource
UINT uID, // resource identifier
LPTSTR lpBuffer, // address of buffer for resource
int nBufferMax // size of buffer
);
Parameters
hInstance
Identifies an instance of the module whose executable file contains the string resource.
uID
Specifies the integer identifier of the string to be loaded.
lpBuffer
Points to the buffer to receive the string.
nBufferMax
Specifies the size of the buffer in bytes (ANSI version) or characters (Unicode version). The string is truncated and null terminated if it is longer than the number of characters specified.
Return Values
If the function succeeds, the return value is the number of bytes (ANSI version) or characters (Unicode version) copied into the buffer, not including the null-terminating character, or zero if the string resource does not exist. To get extended error information, call GetLastError.
[/i] VirtualProtect
[i]
The VirtualProtect function changes the access protection on a region of committed pages in the virtual address space of the calling process. This function differs from VirtualProtectEx, which changes the access protection of any process.
BOOL VirtualProtect(
LPVOID lpAddress, // address of region of committed pages
DWORD dwSize, // size of the region
DWORD flNewProtect, // desired access protection
PDWORD lpflOldProtect // address of variable to get old protection
);
Parameters
lpAddress
Points to the base address of the region of pages whose access protection attributes are to be changed.
All pages in the specified region must have been allocated in a single call to the VirtualAlloc or VirtualAllocEx function. The pages cannot span adjacent regions that were allocated by separate calls to VirtualAlloc or VirtualAllocEx.
dwSize
Specifies the size, in bytes, of the region whose access protection attributes are to be changed. The region of affected pages includes all pages containing one or more bytes in the range from the lpAddress parameter to (
lpAddress+dwSize). This means that a 2-byte range straddling a page boundary causes the protection attributes of both pages to be changed.
flNewProtect
Specifies the new access protection. You can specify any one of the following flags, along with the PAGE_GUARD and PAGE_NOCACHE protection modifier flags, as necessary:
Value Meaning
PAGE_READONLY Enables read access to the committed region of pages. An attempt to write to the committed region results in an access violation. If the system differentiates between read-only access and execute access, an attempt to execute code in the committed region results in an access violation.
PAGE_READWRITE Enables both read and write access to the committed region of pages.
PAGE_WRITECOPY Gives copy-on-write access to the committed region of pages.
PAGE_EXECUTE Enables execute access to the committed region of pages. An attempt to read or write to the committed region results in an access violation.
PAGE_EXECUTE_READ Enables execute and read access to the committed region of pages. An attempt to write to the committed region results in an access violation.
PAGE_EXECUTE_READWRITE Enables execute, read, and write access to the committed region of pages.
PAGE_EXECUTE_WRITECOPY Enables execute, read, and write access to the committed region of pages. The pages are shared read-on-write and copy-on-write.
PAGE_GUARD Pages in the region become guard pages. Any attempt to access a guard page causes the operating system to raise a STATUS_GUARD_PAGE exception and turn off the guard page status. Guard pages thus act as a one-shot access alarm.The PAGE_GUARD flag is a page protection modifier. An application uses it with one of the other page protection flags, with one exception: it cannot be used with PAGE_NOACCESS. When an access attempt leads the operating system to turn off guard page status, the underlying page protection takes over.If a guard page exception occurs during a system service, the service typically returns a failure status indicator.
PAGE_NOACCESS Disables all access to the committed region of pages. An attempt to read from, write to, or execute in the committed region results in an access violation exception, called a general protection (GP) fault.
PAGE_NOCACHE Allows no caching of the committed regions of pages. The hardware attributes for the physical memory should be specified as "no cache." This is not recommended for general usage. It is useful for device drivers; for example, mapping a video frame buffer with no caching. This flag is a page protection modifier, only valid when used with one of the page protections other than PAGE_NOACCESS.
lpflOldProtect
Points to a variable that the function sets to the previous access protection value of the first page in the specified region of pages. If this parameter is NULL or does not point to a valid variable, the function fails.
Return Values
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
Remarks
You can set the access protection value on committed pages only. If the state of any page in the specified region is not committed, the function fails and returns without modifying the access protection of any pages in the specified region.
The VirtualProtect function changes the access protection of memory in the calling process, and the VirtualProtectEx function changes the access protection of memory in a specified process.
The PAGE_GUARD protection modifier flag establishes guard pages. Guard pages act as one-shot access alarms. See Guard Pages for further discussion of guard pages.
[/i]
Если вы заметили орфографическую ошибку на этой странице, просто выделите ошибку мышью и нажмите Ctrl+Enter. Функция может не работать в некоторых версиях броузеров.