EventLog

EventLogは、イベントログを出力するクラス・・・。

EventLog クラス (System.Diagnostics)

イベントログを出力してみる・・・。

空のプロジェクトで、

f:id:BG1:20170321180819p:plain

Systemを参照し、MainClass.csは、

これだけ・・・。
"EventLog_"がイベントソースで、ログが"Log Message!"・・・。
で、何故try-catchで囲むかというと、このまま実行すると、

System.Security.SecurityException: ソースが見つかりませんでしたが、いくつかまた
はすべてのログを検索できませんでした。アクセス不可能なログ: Security
   場所 System.Diagnostics.EventLog.FindSourceRegistration(String source, String
 machineName, Boolean readOnly)
   場所 System.Diagnostics.EventLog.SourceExists(String source, String machineNa
me)
   場所 System.Diagnostics.EventLog.VerifyAndCreateSource(String sourceName, Str
ing currentMachineName)
   場所 System.Diagnostics.EventLog.WriteEntry(String message, EventLogEntryType
 type, Int32 eventID, Int16 category, Byte[] rawData)
   場所 System.Diagnostics.EventLog.WriteEntry(String source, String message, Ev
entLogEntryType type, Int32 eventID, Int16 category, Byte[] rawData)
   場所 System.Diagnostics.EventLog.WriteEntry(String source, String message)
   場所 MainClass.Main() 場所 C:\Project\Cloud\github.com\Sample\dotnet\EventLog
\EventLog\src\EventLog_\EventLog_\MainClass.cs:行 18
失敗したアセンブリのゾーン:
MyComputer
続行するには何かキーを押してください . . .

実は管理者権限で実行すれば成功する・・・。
で、それでもいいが、どうせなので、exeにマニフェストファイルを付けて、管理者権限昇格できるようにしてみた・・・。
しかし、これが結構大変だった・・・。
Visual C# 2005には、マニフェストファイルの追加項目がないので、

そこで、

"C:\Program Files (x86)\Microsoft Visual Studio 8\VC\bin\mt.exe" -manifest "$(ProjectDir)$(TargetFileName).manifest" -outputresource:"$(TargetPath)";1 

これを、

f:id:BG1:20170321181425p:plain

[プロパティ]の[ビルドイベント]の[ビルド後に実行するコマンドライン]にセット・・・。

マニフェストファイルは、WindowsAPIのDispatchMessageからプロジェクトフォルダにもってきたが、ファイル名をEventLog_.exe.manifestにした上で、

level="requireAdministrator"にしないとダメ・・・。

さらに、

f:id:BG1:20170321181805p:plain

ビルド構成がAnyCPUだと、管理者権限アイコンがつかないので、x86に変更・・・。

ここまでしてビルドすると、

f:id:BG1:20170321181946p:plain

管理者権限アイコンがつく・・・。
しかし、VisualStudioが一般権限なので、

f:id:BG1:20170321182038p:plain

管理者で実行・・・。

これでデバッグなしで実行すると、

続行するには何かキーを押してください . . .

例外が出なくなり、

f:id:BG1:20170321182201p:plain

イベントログが出るようになる・・・。

Sample/dotnet/EventLog/EventLog/src/EventLog_ at master · bg1bgst333/Sample · GitHub