Статьи по Делфи
Меню сайта


Категории каталога
Мои статьи [2]
Функции и процедуры Win Api [20]
Работа с мышью [10]
Реестр и Делфи [11]
Работа с файлами [38]
Делфи и Хакер [10]
Инсталлятор собственными руками [6]
Хитрости в делфи [3]
Работа с системой [19]


Форма входа


Поиск по каталогу


Друзья сайта


Наш опрос
Понравились ли вам треки
Всего ответов: 156


Приветствую Вас, Гость · RSS 2024-05-18, 11:11 PM
Начало » Статьи » Функции и процедуры Win Api

Запись сообщений в журнал событий Windows на Delphi
Приложение может записывать сообщения в журнал используя следующие функции WinAPI. Подробное описание параметров этих функций содержится в документации к API.
RegisterEventSource - Открывает handle для доступа к журналу на локальной или удаленной машине.
ReportEvent - Собственно записывает сообщение.

Для записи сообщений в журнал в упрощенной манере просто произведите вызов RegisterEventSource с именем машины (UNC), в журнал которой вы хотите поместить сообщение (nil для локальной машины), и именем события. Имя события это обычно имя приложения, но может быть чем-то более информативным. Как только источник событий зарегистрирован, можно записывать события при помощи ReportEvent с handle, который вернула RegisterEventSource.

Листинг 1. Пример

VAR EventLog:THandle;
EventLog:=RegisterEventSource(nil,PChar(′MyApplication′));

VAR MyMsg:Array[0..2] of PChar;
MyMsg[0]:=′A test event message′;

ReportEvent(EventLog,EVENTLOG_INFORMATION_TYPE,0,0,nil,1,0,@MyMsg,nil);

Однако текст сообщения, записанного в журнал будет предварен текстом: "The description for Event ID ( 0 ) in Source ( MyApplication ) cannot be found. The local computer may not have necessary registry information or message DLL files to display messages from a remote computer. The following information is part of the event:" (Не найдено описание для события с кодом ( 0 ) в источнике ( MyApplication ). Возможно, на локальном компьютере нет нужных данных в реестре или файлов DLL сообщений для отображения сообщений удаленного компьютера. В записи события содержится следующая информация:) (Замечание: Это сообщение специфично для Windows2000 и может немного отличаться на других версиях). Для предотвращения появления этого текста необходимо внести в реестр некоторые ключи, как показано ниже, и определить строковые ресурсы (это может быть выполнено любым компонентом вашего приложения, не обязательно приложением, которое будет записывать события). Соответствующие записи реестра описаны ниже. Примеры кода предполагают, что строковые ресурсы и категории расположены в том же исполняемом файле, который содержит программу, записывающую события. Ключи категорий являются опциональными. Смысл этих ключей реестра и строковых ресурсов в том, что журнал событий использует строку, а приложение записывает в журнал в виде форматированного аргумента, и журналу необходимо знать, где находится описатель формата для этой строки. Кроме того, в журнале может храниться информация о категории события, полезная для просмотра событий. Это удобнее, чем просто отображать множество однотипный событий "Нет". Самый простой определитель формата это %1, который просто передаст в журнал входную строку. Для более подробного изучения определителей формата см. API документацию для FormatMessage.
Ключи реестра

Создайте следующий ключ реестра:

HKEY_LOCAL_MACHINESYSTEM - CurrentControlSet - Services - Eventlog - Application -

Имя приложения AppName должно совпадать с именем источника, использованного при вызове RegisterEventSource, потому что просмотрщик событий будет использовать это имя для отыскивания событий.

Создайте следующие ключи:

CategoryCount (Optional) - Integer - Количество категорий событий, которые вы собираетесь использовать. (Это максимальная величина, и не будет проблем, если не все категории на самом деле будут применяться).
CategoryMessageFile (Optional) - String - Файл, содержащий ресурсы строк категорий.
EventMessageFile - String - Файл, содержащий ресурсы строк событий.
TypesSupported - Integer - Допустимые типы событий.

Листинг 2. Пример кода для создания необходимых записей в реестре

VAR
Reg:TRegistry;
RegKey:String;
AppPath:String;
AppName:String;
NumCategories:Integer;

Begin
Reg:=TRegistry.Create;
Try
AppPath:=Application.ExeName;
AppName:=′MyApplication′;
NumCategories:=2;
RegKey:=
Format(′SYSTEMCurrentControlSetServicesEventLogApplication%s′,[AppName]);
Reg.RootKey:=HKEY_LOCAL_MACHINE;
Reg.OpenKey(RegKey,True);
// Собственное имя
Reg.WriteString(′CategoryMessageFile′,AppPath);
// Собственное имя
Reg.WriteString(′EventMessageFile′,AppPath);
// Максимальное количество категорий
Reg.WriteInteger(′CategoryCount′,NumCategories);
// Разрешаем все типы
Reg.WriteInteger(′TypesSupported′,EVENTLOG_SUCCESS or
EVENTLOG_ERROR_TYPE or
EVENTLOG_WARNING_TYPE or
EVENTLOG_INFORMATION_TYPE);
Reg.CloseKey;
EventLog:=RegisterEventSource(nil,PChar(AppName));
Finally
Reg.Free;
End; //try..finally

End;

Сообщение и ресурсы категорий.

Информация, помещаемая в реестр вышеприведенным кодом, информирует журнал событий о том, где искать строки событий и категорий, основываясь на имени источника, которое использует приложение для записи в журнал. И, как мы уже говорили, чтобы журнал событий искал эти строки в нашем исполняемом файле, нам нужно включить эти строковые ресурсы в наш файл. Этот процесс состоит из следующих шагов:
Написание исходного файла таблицы сообщений (файл .mc).
Компиляция .mc файла при помощи Microsoft message compiler.
Подключение получившейся информации к нашему Delphi приложению.

Есть много примеров по написанию .mc файлов в Windows SDK и на различных сайтах, включая MSDN, однако документация не достаточно проста, поэтому приводим минимально достаточное описание для создания файла таблицы сообщений:

Листинг 3. Код Delphi/Pascal

;//Example Message source file exmess.mc
MessageId=0
Language=English
%1
.

MessageId=1
Language=English
Category1
.

MessageId=2
Language=English
Category2
.

Строки, начинающиеся с ;// являются комментариями и не компилируются. Этот пример содержит три строковых ресурса - один определитель формата сообщения и две категории, хотя файл может содержать только первый ресурс. Каждый ресурс отделен одной отдельной точкой на строке, так же, как и в конце файла. Если в конце файла отсутствует перевод строки после точки, то файл не будет скомпилирован. Первая строка каждого ресурса является MessageID (index), при помощи которого приложение будет обращаться к строке. Следующая строка указывает язык ресурса. В нашем случае "English" - означает international English, язык по умолчанию для всех Windows платформ. Информацию по многоязыковым ресурсам см. в справке к компилятору ресурсов. Последняя строка определяет собственно текст сообщения. В случае ресурса 0, строка будет "%1", что означает, что передается сама строка. Если, например, нужен префикс сообщения "An Event Message" (Сообщение события), то строка будет иметь вид: "An Event Message %1". Более полное описание форматов см. в API справке по FormatMessage и компилятору ресурсов. Ресурсы категорий не требуют форматированных аргументов. Как видно в примере, мы определили две категории "Category1" и "Category2". Следующий этап - компиляция .mc файла при помощи Microsoft message compiler (mc.exe), который можно взять у Microsoft (входит в состав Platform SDK). Наш пример, имеющий имя "exmess.mc" может быть скомпилирован из командной строки таким образом:

Mc exmess.mc

В результате получаем три файла: exmess.rc, bin00001.msg и exmess.h. emess.h может быть использован как заголовочный файл для обращения к ресурсам по их символическим именам, если таковые указаны (в нашем примере нет). .bin файл это откомпилированный бинарный ресурс с сообщениями, .rc это файл ресурсов Windows. Он может быть откомпилирован в Delphi .res файл при помощи brcc32.exe - компилятора ресурсов Delphi или просто добавлен в проект при помощи project manager, и тогда Delphi автоматически его откомпилирует при компиляции проекта (build).

Запись событий с категориями.

Теперь наше приложение имеет ресурсы и необходимые записи в реестре или код, который их внесет. Значит, приложение может записывать события в журнал без сообщения об отсутствии ресурсов и с добавочным индексом категории события:

Листинг 4. Код Delphi/Pascal

VAR EventLog: THandle;
EventLog:=RegisterEventSource(nil,PChar(′MyApplication′));

VAR MyMsg:Array[0..2] of PChar;
MyMsg[0]:=′A test event message′;

ReportEvent(EventLog, EVENTLOG_INFORMATION_TYPE,1,0,nil,1,0,@MyMsg,nil);

Вышеприведенный код запишет событие в журнал с текстом "A test event message" и, потому что 1 следует за параметром EventLogType, это будет событие категории "Category1". Это достигнуто указанием 0 в качестве идентификатора события, который соответствует определителю формата в ресурсе 0 ("%1"). В результате текст сообщения события будет передан без изменения. Точно так же, категория указана 1, что соответствует "Category1" в нашем ресурсе 1. Журнал событий поддерживает "живую связь" с файлами сообщений и категорий, указанных в реестре, что означает, что когда пользователь захочет просмотреть журнал, просмотрщик событий получит доступ к файлам ресурсов для детального отображения событий. Это также означает, что если вы создадите множество событий, при помощи указанного файла ресурсов, и, затем, измените значения в файле ресурсов и произведете обновление (refresh) в просмотрщике событий, тексты событий и номера категорий так же изменятся в соответствии с ресурсами. Точно так же, если файл ресурсов вдруг будет удален или записи в реестре будут уничтожены или повреждены, то журнал не сможет получить доступ к ресурсам, и отобразит сообщение с ошибкой в виде префикса события, как было описано в начале статьи. В этом случае вместо номера категории события будет отображен индекс категории.

Категория: Функции и процедуры Win Api | Добавил: Admin (2006-12-16) | Автор: M@ster
Просмотров: 103769 | Комментарии: 2342 | Рейтинг: 5.0 |

Всего комментариев: 12841 2 3 ... 128 129 »
1284 Jaredobjem  
0
New mission could shed light on the secrets of the moon’s ‘hidden side
<a href=https://cryptobosscasino03.com>cryptoboss casino зеркало</a>
Over the past few years, competing countries have turned the moon into a hotspot for activity not witnessed since the Apollo 17 astronauts departed from the lunar surface in 1972.

In one lunar region, Japan’s “Moon Sniper” mission has beaten the odds and survived three long, frigid lunar nights since its sideways landing on January 19.
https://cryptobosscasino03.com
cryptoboss рабочее зеркало
Engineers at the Japan Aerospace Exploration Agency didn’t design the spacecraft to last through one lunar night, a two-week period of freezing darkness, but the Moon Sniper continues to thrive amid lunar extremes and send back new images of its landing site.

Elsewhere, an international team of astronomers believes it has homed in on a crater created a few million years ago when something massive slammed into the lunar surface — and sent a chunk of the moon’s far side, or the side that faces away from Earth, hurtling into space. The hunk of moon became a rare quasi-satellite, or asteroid that orbits near Earth.

The Tianwen-2 mission will visit the space rock later this decade. But first, China has set its sights on returning to the moon’s “hidden side.”
The Chang’e-6 mission, which launched Friday, is aiming to bring back the first samples from the South Pole-Aitken basin, or the largest and oldest crater on the moon. Since the Chang’e 4 mission in 2019, China remains the only country to have landed on the moon’s far side, sometimes called the “dark side” of the moon.

The “dark side” of the moon is actually a misnomer, experts say, and the remote lunar hemisphere receives illumination — scientists just don’t know as much about the region as they’d like.

The far side, with its thicker crust, is vastly different from the near side that was explored during the Apollo missions.

Scientists hope that returning samples from the far side could solve some of the biggest remaining lunar mysteries, including the moon’s true origin.

1283 TravisIncex  
0
2024 NFL Draft: 5 quarterbacks taken in the top 10 of the NFL Draft for the first time ever
<a href=https://kraken13v.at>kraken войти</a>
The 2024 NFL Draft has kicked off with the Chicago Bears selecting USC quarterback Caleb Williams with the first overall pick on Thursday night.

Bears fans at the event applauded Williams as he walked onto the stage to share an embrace with NFL commissioner Roger Goodell.

This year’s draft could well be be a blockbuster one, with heaps of highly-touted quarterback talents, a potentially all-time wide receiver group and overall value throughout. It’s the first time in NFL history five quarterbacks were selected in the top 10, and there are plenty more teams searching for an answer at the position.
https://kraken13v.at
kraken войти
With teams loaded on veteran players, the draft allows the 32 franchises to stock up on young prospects before heading into training camp to fine tune their rosters ahead of the opening of the new season in September.

Earlier Thursday, NFL spokesperson Brian McCarthy said on X 150,000 fans are in attendance at the draft.

Here’s everything you need to know about the 2024 NFL Draft.

There are some years where the crop of quarterbacks coming out of college football isn’t awe-inspiring.

This is not one of those years.

There are a number of potentially franchise-changing signal-callers in the 2024 class, and chief among those was USC’s Williams.

Although he endured somewhat of a down year last season, Williams possesses all the attributes required to be a high-level quarterback in the NFL.

His throwing ability in various scenarios combined with his athletic talents make him the perfect example of the modern dual-threat QB and have led to comparisons to former No. 1 overall pick Kyler Murray.

The 22-year-old Williams has been high on many draft analysts’ radar for over a year now, following his Heisman Trophy winning season in 2022; he broke Trojan records in passing touchdowns, passing yards and passing efficiency that season.

1282 StevenDyemi  
0
2024 NFL Draft: 5 quarterbacks taken in the top 10 of the NFL Draft for the first time ever
<a href=https://kraken13v.at>kraken войти</a>
The 2024 NFL Draft has kicked off with the Chicago Bears selecting USC quarterback Caleb Williams with the first overall pick on Thursday night.

Bears fans at the event applauded Williams as he walked onto the stage to share an embrace with NFL commissioner Roger Goodell.

This year’s draft could well be be a blockbuster one, with heaps of highly-touted quarterback talents, a potentially all-time wide receiver group and overall value throughout. It’s the first time in NFL history five quarterbacks were selected in the top 10, and there are plenty more teams searching for an answer at the position.
https://kraken13v.at
kraken тор
With teams loaded on veteran players, the draft allows the 32 franchises to stock up on young prospects before heading into training camp to fine tune their rosters ahead of the opening of the new season in September.

Earlier Thursday, NFL spokesperson Brian McCarthy said on X 150,000 fans are in attendance at the draft.

Here’s everything you need to know about the 2024 NFL Draft.

There are some years where the crop of quarterbacks coming out of college football isn’t awe-inspiring.

This is not one of those years.

There are a number of potentially franchise-changing signal-callers in the 2024 class, and chief among those was USC’s Williams.

Although he endured somewhat of a down year last season, Williams possesses all the attributes required to be a high-level quarterback in the NFL.

His throwing ability in various scenarios combined with his athletic talents make him the perfect example of the modern dual-threat QB and have led to comparisons to former No. 1 overall pick Kyler Murray.

The 22-year-old Williams has been high on many draft analysts’ radar for over a year now, following his Heisman Trophy winning season in 2022; he broke Trojan records in passing touchdowns, passing yards and passing efficiency that season.

1281 Stephencop  
0
New mission could shed light on the secrets of the moon’s ‘hidden side
<a href=https://cryptobosscasino03.com>криптобосс сайт</a>
Over the past few years, competing countries have turned the moon into a hotspot for activity not witnessed since the Apollo 17 astronauts departed from the lunar surface in 1972.

In one lunar region, Japan’s “Moon Sniper” mission has beaten the odds and survived three long, frigid lunar nights since its sideways landing on January 19.
https://cryptobosscasino03.com
cryptoboss
Engineers at the Japan Aerospace Exploration Agency didn’t design the spacecraft to last through one lunar night, a two-week period of freezing darkness, but the Moon Sniper continues to thrive amid lunar extremes and send back new images of its landing site.

Elsewhere, an international team of astronomers believes it has homed in on a crater created a few million years ago when something massive slammed into the lunar surface — and sent a chunk of the moon’s far side, or the side that faces away from Earth, hurtling into space. The hunk of moon became a rare quasi-satellite, or asteroid that orbits near Earth.

The Tianwen-2 mission will visit the space rock later this decade. But first, China has set its sights on returning to the moon’s “hidden side.”
The Chang’e-6 mission, which launched Friday, is aiming to bring back the first samples from the South Pole-Aitken basin, or the largest and oldest crater on the moon. Since the Chang’e 4 mission in 2019, China remains the only country to have landed on the moon’s far side, sometimes called the “dark side” of the moon.

The “dark side” of the moon is actually a misnomer, experts say, and the remote lunar hemisphere receives illumination — scientists just don’t know as much about the region as they’d like.

The far side, with its thicker crust, is vastly different from the near side that was explored during the Apollo missions.

Scientists hope that returning samples from the far side could solve some of the biggest remaining lunar mysteries, including the moon’s true origin.

1280 LouisLoody  
0
New mission could shed light on the secrets of the moon’s ‘hidden side
<a href=https://cryptobosscasino03.com>cryptoboss casino бездепозитный бонус</a>
Over the past few years, competing countries have turned the moon into a hotspot for activity not witnessed since the Apollo 17 astronauts departed from the lunar surface in 1972.

In one lunar region, Japan’s “Moon Sniper” mission has beaten the odds and survived three long, frigid lunar nights since its sideways landing on January 19.
https://cryptobosscasino03.com
cryptoboss
Engineers at the Japan Aerospace Exploration Agency didn’t design the spacecraft to last through one lunar night, a two-week period of freezing darkness, but the Moon Sniper continues to thrive amid lunar extremes and send back new images of its landing site.

Elsewhere, an international team of astronomers believes it has homed in on a crater created a few million years ago when something massive slammed into the lunar surface — and sent a chunk of the moon’s far side, or the side that faces away from Earth, hurtling into space. The hunk of moon became a rare quasi-satellite, or asteroid that orbits near Earth.

The Tianwen-2 mission will visit the space rock later this decade. But first, China has set its sights on returning to the moon’s “hidden side.”
The Chang’e-6 mission, which launched Friday, is aiming to bring back the first samples from the South Pole-Aitken basin, or the largest and oldest crater on the moon. Since the Chang’e 4 mission in 2019, China remains the only country to have landed on the moon’s far side, sometimes called the “dark side” of the moon.

The “dark side” of the moon is actually a misnomer, experts say, and the remote lunar hemisphere receives illumination — scientists just don’t know as much about the region as they’d like.

The far side, with its thicker crust, is vastly different from the near side that was explored during the Apollo missions.

Scientists hope that returning samples from the far side could solve some of the biggest remaining lunar mysteries, including the moon’s true origin.

1279 Jerryplubs  
0
New mission could shed light on the secrets of the moon’s ‘hidden side
<a href=https://cryptobosscasino03.com>cryptoboss</a>
Over the past few years, competing countries have turned the moon into a hotspot for activity not witnessed since the Apollo 17 astronauts departed from the lunar surface in 1972.

In one lunar region, Japan’s “Moon Sniper” mission has beaten the odds and survived three long, frigid lunar nights since its sideways landing on January 19.
https://cryptobosscasino03.com
cryptoboss casino официальный
Engineers at the Japan Aerospace Exploration Agency didn’t design the spacecraft to last through one lunar night, a two-week period of freezing darkness, but the Moon Sniper continues to thrive amid lunar extremes and send back new images of its landing site.

Elsewhere, an international team of astronomers believes it has homed in on a crater created a few million years ago when something massive slammed into the lunar surface — and sent a chunk of the moon’s far side, or the side that faces away from Earth, hurtling into space. The hunk of moon became a rare quasi-satellite, or asteroid that orbits near Earth.

The Tianwen-2 mission will visit the space rock later this decade. But first, China has set its sights on returning to the moon’s “hidden side.”
The Chang’e-6 mission, which launched Friday, is aiming to bring back the first samples from the South Pole-Aitken basin, or the largest and oldest crater on the moon. Since the Chang’e 4 mission in 2019, China remains the only country to have landed on the moon’s far side, sometimes called the “dark side” of the moon.

The “dark side” of the moon is actually a misnomer, experts say, and the remote lunar hemisphere receives illumination — scientists just don’t know as much about the region as they’d like.

The far side, with its thicker crust, is vastly different from the near side that was explored during the Apollo missions.

Scientists hope that returning samples from the far side could solve some of the biggest remaining lunar mysteries, including the moon’s true origin.

1278 canadian prescriptions online  
0
Great items from you, man. I've be aware your stuff previous to and you are simply too wonderful. I really like what you have bought here, certainly like what you're saying and the way by which you assert it. You make it enjoyable and you still take care of to stay it wise. I can not wait to read far more from you. That is really a great website.

1277 canadian pharmaceuticals online shipping  
0
It's amazing to pay a quick visit this site and reading the views of all friends concerning this piece of writing, while I am also keen of getting know-how.

1276 RichardMap  
0
‘Win the trophy. That’s what we can achieve,’ says Trent Alexander-Arnold of England’s chances at Euro 2024
<a href=https://kraken13c.at>kraken зеркало</a>

Liverpool star Trent Alexander-Arnold says that the England squad will head to Euro 2024 believing it can win the European Championship in Germany this summer.

Speaking to CNN’s Senior Sports Analyst Darren Lewis, the Three Lions defender was bullish about England’s chances at the Euros.
https://kraken13c.at
kraken зайти

“People will say we’re one of the favorites. It’s the furthest thing from arrogance, but you have to have confidence and believe you can win it, otherwise you can’t.

“If you don’t believe you can, then you never will. So, look, we’ll go out there as a team. We’ll believe we can. But we know we have to perform in the way that we know we can to go and do it.”

Alexander-Arnold hasn’t featured much in 2024 due to a knee injury; the 25-year-old has recently returned to action in the Premier League with Liverpool, scoring a sublime free-kick against Fulham in a 3-1 win on April 21 for the Merseyside club.

Now, his goal is to prove to England boss Gareth Southgate that he is worth a place in the squad and build on his 23 international appearances.
It might surprise people to hear where Alexander-Arnold believes is his best position for the national team: in midfield alongside Real Madrid’s Jude Bellingham.

“I would say midfield, I think, in an England shirt,” said Alexander-Arnold, who usually plays for Liverpool in defense as a right-back.

“I see myself as a midfielder, and that’s down to the conversations I’ve had with the manager,” he added.

“If it comes down to it, look, clearly I can play at right back and I can do a good job there. But with the conversations I’ve had with the manager and how he’s kind of spoken to me about the position, it is a midfield role – I see an opportunity there.”

Alexander-Arnold was ruled out of Euro 2020 after sustaining a thigh injury in the build-up to the competition and missed being part of England’s run to the final, where the Three Lions ultimately lost on penalties to Italy. During the 2022 World Cup, the Liverpool star was an unused substitute on four occasions and played just 33 minutes in Qatar.

1275 DmhskcTem  
0
Recently, I've been enthusiastic about making a couple of wagers on numerous sports matches occurring at the moment. I figured I should let know all of you that I have come across what I believe to be the most dependable site throughout the USA. If you happen to be keen on getting involved in the fun, be sure to visit this online destination: <a href=https://purecasinos.org/new/>purecasinos.org/new/</a>

1-10 11-20 21-30 ... 1271-1280 1281-1284
Имя *:
Email *:
Код *: