Código fuente completo de la aplicación ProyectoA Notificaciones Windows TOAST. Esta aplicación permite pasarle un fichero JSON por argumento de la línea de comandos para mostrar un mensaje TOAST nativo de Windows, integrado con el Centro de Notificaciones de Windows. Dicho mensaje es personalizable a través de un fichero JSON: asunto, cuerpo, imagen lateral, imagen superior, imagen en el mensaje, pie, botón de cerrar y botón de acción.
- Funcionamiento de la aplicación ProyectoA Notificaciones Windows.
- Descarga del código fuente en Delphi 12.2 y del ejecutable de la aplicación.
- Código fuente en Delphi 12.2 de la unidad principal de la aplicación UnidadNotificacion.pas.
- Anexo: ejemplo en C# para ejecutar la aplicación de notificaciones.
Funcionamiento de la aplicación ProyectoA Notificaciones Windows
ProyectoA Notificaciones Windows es una aplicación de línea de comandos diseñada para mostrar notificaciones nativas en sistemas operativos Windows 10 y 11. Su propósito es recibir la información de una notificación a través de un fichero de configuración en formato JSON y presentarla al usuario.
La aplicación se ejecuta de forma silenciosa en segundo plano, muestra la notificación y se cierra automáticamente.
La aplicación permite mostrar mensajes nativos Windows VCL, simples, con este aspecto:

O bien notificaciones más avanzadas con imágenes y botones de acción:

Para ejecutar la aplicación, se debe invocar desde la línea de comandos (CMD o PowerShell), pasándole como único argumento la ruta completa al fichero JSON que contiene la configuración de la notificación.
Sintaxis:
|
1 |
NotificacionesWindows.exe "C:Notificacionesnotificacion_informe_ventas.json" |
Estructura de ficheros que genera/usa la aplicación
La aplicación utiliza y genera varios ficheros en su directorio de ejecución para funcionar:
- config.json (Configuración Global):
- notificacion_template.xml (Plantilla de Diseño):
- mensaje.json (Contenido del Mensaje):
- Notificacion.log (Log de Actividad):
- Notificacion.historial.json (Historial de Duplicados):
Fichero de Configuración (config.json)
Este fichero permite personalizar el comportamiento global de la aplicación.
| Clave | Descripción | Valor por Defecto |
| app_id | Identificador único de la aplicación para Windows. Es importante para que Windows agrupe las notificaciones. | ProyectoA.Notificaciones |
| app_display_name | El nombre que se muestra en el Menú Inicio y en la configuración de notificaciones de Windows. | ProyectoA Notificaciones |
| minutos_limite_duplicados | Tiempo en minutos para evitar mostrar notificaciones idénticas (mismo título y cuerpo). | 120 |
| icono_notificacion | (Opcional) Ruta a un fichero .ico para usar en el acceso directo del Menú Inicio. Si está vacío, se usa el icono del ejecutable. | «» |
| ruta_xml_template | (Opcional) Nombre del fichero de plantilla XML para las notificaciones PowerShell. | notificacion_template.xml |
Parámetros del fichero JSON para formar el mensaje
El fichero de composición del mensaje debe ser un documento de texto en formato JSON que define la apariencia y el comportamiento de la notificación. A continuación se detallan todos los parámetros disponibles.
Parámetros Básicos (Obligatorios)
| Clave | Tipo | Descripción |
| titulo | String | El texto principal que aparece en la primera línea de la notificación. Es obligatorio. |
| cuerpo | String | El texto del mensaje. Para crear múltiples líneas, se pude utilizar el carácter de nueva línea n. Es obligatorio. |
Parámetros Avanzados (opcionales, para tipo_notificacion: «powershell»)
Estos parámetros solo tienen efecto si se especifica «tipo_notificacion»: «powershell».
| Clave | Tipo | Descripción |
| tipo_notificacion | String | Define el método de visualización de las notificaciones: nativo de Windows con la app (VCL) o PowerShell. Opciones: «normal» (notificación VCL simple) o «powershell» (notificación Toast avanzada con PowerShell). Por defecto es «normal». |
| duracion | String | Controla el tiempo que la notificación permanece visible en pantalla antes de pasar al Centro de Actividades. Opciones: «corta» (por defecto) o «larga». |
| pie_notificacion | String | Un texto corto que aparece en la parte inferior de la notificación con una fuente más pequeña. Ideal para indicar el origen del mensaje (ej: «Generado por ProyectoA»). |
| mostrar_boton_cerrar | Boolean | Si se establece en true, se mostrará un botón «Cerrar» explícito en la notificación. Por defecto es false. |
| accion_principal | String | Una URL o un protocolo de aplicación (ej: https://…, mailto:…) que se ejecutará si el usuario hace clic en la notificación o en el botón «Abrir». Si se define este parámetro, aparecerá un botón «Abrir». |
| imagen_logo | String | Ruta completa a un fichero de imagen (ej: «D:logosicono.png»). Se mostrará como un icono pequeño a la izquierda del texto. |
| imagen_arriba | String | Ruta completa a un fichero de imagen. Se mostrará como un banner grande en la parte superior. Recomendación de tamaño: relación de aspecto 2:1 (ej: 364×180 píxeles). |
| imagen_inline | String | Ruta completa a un fichero de imagen. Se mostrará debajo del texto principal, ocupando todo el ancho de la notificación. |
Nota sobre las imágenes: las claves imagen_logo, imagen_arriba, y imagen_inline son independientes y pueden usarse solas o en combinación. Si la ruta a un fichero de imagen es inválida o no se proporciona, simplemente no se mostrará esa imagen, sin generar errores.
Plantilla de Notificación (notificacion_template.xml)
Este fichero permite personalizar la estructura del XML de las notificaciones. Debe seguirse la documentación de Microsoft a tal efecto. La aplicación reemplaza los marcadores ##…## con el contenido correspondiente. Si un marcador no tiene contenido (por ejemplo, no se proporciona imagen_logo), toda la línea se elimina.
Contenido por defecto:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<toast##ToastAttributes##> <visual> <binding template="ToastGeneric"> ##LogoImageXML## ##HeroImageXML## <text>$Titulo</text> <text>$Cuerpo</text> ##InlineImageXML## ##PieXML## </binding> </visual> ##ActionsXML## </toast> |
Ejemplos de Ficheros JSON
Ejemplo 1: Notificación simple
|
1 2 3 4 |
{ "titulo": "Tarea Finalizada", "cuerpo": "El proceso de exportación de datos ha concluido satisfactoriamente." } |
Ejemplo 2: Notificación PowerShell avanzada
|
1 2 3 4 5 6 7 8 9 10 11 12 |
{ "titulo": "Informe anual disponible", "cuerpo": "Ya se encuentra disponible el informe anual de ventas. Puede consultarlo pulsando en Abrir.nLas ventas han aumentado un 15%.", "tipo_notificacion": "powershell", "duracion": "larga", "pie_notificacion": "-- Notificación ProyectoA --", "mostrar_boton_cerrar": true, "accion_principal": "https://proyectoa.com", "imagen_arriba": "D:GitDelphiNotificaciones_WindowsWin64Releaseinforme.png", "imagen_logo": "D:GitDelphiNotificaciones_WindowsWin64Releaselogo.png", "imagen_inline": "D:GitDelphiNotificaciones_WindowsWin64Releasegrafica_inversion.png" } |
Ejemplo 3: Notificación PowerShell con solo botón Cerrar
|
1 2 3 4 5 6 7 |
{ "titulo": "Alerta de Sistema", "cuerpo": "El uso de disco en el servidor principal ha superado el 95%.", "tipo_notificacion": "powershell", "mostrar_boton_cerrar": false, "accion_principal": "https://proyectoa.com", } |
Ejemplo 4: Notificación PowerShell con solo botón Abrir
|
1 2 3 4 5 6 |
{ "titulo": "Alerta de Sistema", "cuerpo": "El uso de disco en el servidor principal ha superado el 95%.", "tipo_notificacion": "powershell", "mostrar_boton_cerrar": true } |
Ejemplo 5: Notificación PowerShell sin imagen superior
|
1 2 3 4 5 6 7 8 9 10 11 |
{ "titulo": "Informe anual disponible", "cuerpo": "Ya se encuentra disponible el informe anual de ventas. Puede consultarlo pulsando en Abrir.nLas ventas han aumentado un 15%.", "tipo_notificacion": "powershell", "duracion": "larga", "pie_notificacion": "-- Notificación ProyectoA --", "mostrar_boton_cerrar": true, "accion_principal": "https://proyectoa.com", "imagen_logo": "D:GitDelphiNotificaciones_WindowsWin64Releaselogo.png", "imagen_inline": "D:GitDelphiNotificaciones_WindowsWin64Releasegrafica_inversion.png" } |
Ejemplo 6: Notificación PowerShell sin imagen superior y sin imagen en mensaje
|
1 2 3 4 5 6 7 8 9 10 |
{ "titulo": "Informe anual disponible", "cuerpo": "Ya se encuentra disponible el informe anual de ventas. Puede consultarlo pulsando en Abrir.nLas ventas han aumentado un 15%.", "tipo_notificacion": "powershell", "duracion": "larga", "pie_notificacion": "-- Notificación ProyectoA --", "mostrar_boton_cerrar": true, "accion_principal": "https://proyectoa.com", "imagen_logo": "D:GitDelphiNotificaciones_WindowsWin64Releaselogo.png" } |
Archivos generados por la aplicación
La aplicación crea dos ficheros auxiliares en el mismo directorio donde se encuentra el ejecutable:
- NotificacionesWindows.log (Log de Actividad):
- NotificacionesWindows.historial.json (Historial de notificaciones):
Requisitos del sistema para la ejecución de la aplicación
- Sistema Operativo: Windows 10 o Windows 11.
- Acceso directo en el Menú Inicio: para que las notificaciones avanzadas de tipo PowerShell funcionen correctamente, la aplicación debe tener un acceso directo en el Menú Inicio de Windows. La aplicación creará este acceso directo automáticamente la primera vez que se ejecute. Este paso es necesario para que Windows pueda asociar las notificaciones con la aplicación a través de su AppUserModel.ID.
Descarga del código fuente en Delphi 12.2 y del ejecutable de la aplicación
A continuación, mostramos la descarga del código fuente completo en Delphi 12.2 de la aplicación ProyectoA Notificaciones Windows Toast, la descarga incluye el fichero ejecutable de la aplicación y ficheros de ejemplo JSON:
Código fuente en Delphi 12.2 de la unidad principal de la aplicación UnidadNotificacion.pas
A continuación, mostramos el código fuente de la aplicación ProyectoA Notificaciones Windows TOAST
Código fuente del fichero del proyecto NotificacionesWindows.dpr
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
program NotificacionesWindows; uses Vcl.Forms, UnidadNotificacion in 'UnidadNotificacion.pas' {formNotificacionesWindows}; {$R *.res} begin Application.Initialize; Application.MainFormOnTaskbar := False; Application.CreateForm(TformNotificacionesWindows, formNotificacionesWindows); Application.Run; end. |
Código fuente del fichero UnidadNotificacion.pas
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 |
unit UnidadNotificacion; interface uses Winapi.Windows, Winapi.ShellAPI, Winapi.ShlObj, Winapi.ActiveX, Winapi.PropSys, System.SysUtils, System.Classes, System.Notification, System.JSON, System.IOUtils, System.NetEncoding, System.Win.ComObj, System.DateUtils, System.Win.Registry, System.StrUtils, Vcl.Forms, Vcl.ExtCtrls, Vcl.Controls; const IID_IPersistFile: TGUID = '{0000010b-0000-0000-C000-000000000046}'; PKEY_AppUserModel_ID: TPropertyKey = ( fmtid: '{9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}'; pid: 5 ); type // Almacena la configuración global cargada desde config.json. TAppConfig = record AppID: string; AppDisplayName: string; MinutosLimiteDuplicados: Integer; IconoNotificacion: string; RutaXmlTemplate: string; end; TformNotificacionesWindows = class(TForm) CentroNotificaciones: TNotificationCenter; Temporizador: TTimer; procedure FormCreate(Sender: TObject); procedure TemporizadorTimer(Sender: TObject); private FConfig: TAppConfig; FRutaArchivoLog: string; FRutaArchivoMensaje: string; FRutaArchivoHistorial: string; procedure CargarConfiguracion; procedure CreateParams(var Params: TCreateParams); override; procedure ConfigurarRegistroNotificaciones; procedure EscribirLog(const Mensaje: string; EsError: Boolean = False); procedure MostrarNotificacionDesdeJSON; procedure MostrarNotificacionPowerShell(const Titulo, Cuerpo: string; DatosJSON: TJSONObject); procedure EjecutarComandoPowershell(const Script: string); function HaSidoMostradaRecientemente(const ATitulo, ACuerpo: string): Boolean; procedure RegistrarNotificacionEnHistorial(const ATitulo, ACuerpo: string); procedure CrearAccesoDirectoConAppID; end; var formNotificacionesWindows: TformNotificacionesWindows; implementation {$R *.dfm} procedure TformNotificacionesWindows.CreateParams(var Params: TCreateParams); begin // Se sobreescribe este método para eliminar el estilo WS_VISIBLE antes de que // la ventana se cree, asegurando que el formulario nunca sea visible. inherited CreateParams(Params); Params.Style := Params.Style and not WS_VISIBLE; end; procedure TformNotificacionesWindows.FormCreate(Sender: TObject); begin try FRutaArchivoLog := ChangeFileExt(Application.ExeName, '.log'); FRutaArchivoHistorial := ChangeFileExt(Application.ExeName, '.historial.json'); CargarConfiguracion; ConfigurarRegistroNotificaciones; if ParamCount = 0 then begin EscribirLog('No se especificó un archivo JSON de mensaje como parámetro.', True); Application.Terminate; Exit; end; FRutaArchivoMensaje := ParamStr(1); if not FileExists(FRutaArchivoMensaje) then begin EscribirLog('El archivo de mensaje "' + FRutaArchivoMensaje + '" no existe.', True); Application.Terminate; Exit; end; CrearAccesoDirectoConAppID; // Se usa un temporizador corto para desacoplar la lógica principal del evento // FormCreate, permitiendo que el formulario se cargue completamente en memoria // antes de ejecutar la acción principal y cerrar la aplicación. Temporizador.Interval := 100; Temporizador.Enabled := True; except on E: Exception do begin EscribirLog('Error durante la inicialización: ' + E.Message, True); Vcl.Forms.Application.Terminate; end; end; end; procedure TformNotificacionesWindows.CargarConfiguracion; var RutaConfig: string; DatosJSON: TJSONObject; TemplateContent: TStringList; begin RutaConfig := TPath.Combine(ExtractFilePath(Application.ExeName), 'config.json'); if not FileExists(RutaConfig) then begin EscribirLog('No se encontró el fichero de configuración. Se crea "config.json" por defecto.'); DatosJSON := TJSONObject.Create; try DatosJSON.AddPair('app_id', 'ProyectoA.Notificaciones'); DatosJSON.AddPair('app_display_name', 'ProyectoA Notificaciones'); DatosJSON.AddPair('minutos_limite_duplicados', TJSONNumber.Create(120)); DatosJSON.AddPair('icono_notificacion', ''); DatosJSON.AddPair('ruta_xml_template', 'notificacion_template.xml'); TFile.WriteAllText(RutaConfig, DatosJSON.ToJSON); finally DatosJSON.Free; end; end; DatosJSON := TJSONObject.ParseJSONValue(TFile.ReadAllText(RutaConfig)) as TJSONObject; if Assigned(DatosJSON) then begin try FConfig.AppID := DatosJSON.GetValue<string>('app_id', 'Default.AppID'); FConfig.AppDisplayName := DatosJSON.GetValue<string>('app_display_name', 'Default Display Name'); FConfig.MinutosLimiteDuplicados := DatosJSON.GetValue<Integer>('minutos_limite_duplicados', 120); FConfig.IconoNotificacion := DatosJSON.GetValue<string>('icono_notificacion', ''); FConfig.RutaXmlTemplate := TPath.Combine(ExtractFilePath(Application.ExeName), DatosJSON.GetValue<string>('ruta_xml_template', 'notificacion_template.xml')); finally DatosJSON.Free; end; end; if not FileExists(FConfig.RutaXmlTemplate) then begin EscribirLog('No se encontró el fichero de plantilla XML. Se crea "' + FConfig.RutaXmlTemplate + '" por defecto.'); TemplateContent := TStringList.Create; try TemplateContent.Add('<toast##ToastAttributes##>'); TemplateContent.Add(' <visual>'); TemplateContent.Add(' <binding template="ToastGeneric">'); TemplateContent.Add('##LogoImageXML##'); TemplateContent.Add('##HeroImageXML##'); TemplateContent.Add(' <text>$Titulo</text>'); TemplateContent.Add(' <text>$Cuerpo</text>'); TemplateContent.Add('##InlineImageXML##'); TemplateContent.Add('##PieXML##'); TemplateContent.Add(' </binding>'); TemplateContent.Add(' </visual>'); TemplateContent.Add('##ActionsXML##'); TemplateContent.Add('</toast>'); TemplateContent.SaveToFile(FConfig.RutaXmlTemplate); finally TemplateContent.Free; end; end; end; procedure TformNotificacionesWindows.ConfigurarRegistroNotificaciones; var Reg: TRegistry; begin Reg := TRegistry.Create; try Reg.RootKey := HKEY_CURRENT_USER; if Reg.OpenKey('SoftwareMicrosoftWindowsCurrentVersionNotificationsSettings' + FConfig.AppID, True) then begin Reg.WriteString('DisplayName', FConfig.AppDisplayName); Reg.CloseKey; EscribirLog('Se crea clave de registro SoftwareMicrosoftWindowsCurrentVersionNotificationsSettings' + FConfig.AppID); end; finally Reg.Free; end; end; procedure TformNotificacionesWindows.TemporizadorTimer(Sender: TObject); begin Temporizador.Enabled := False; try MostrarNotificacionDesdeJSON; finally Application.Terminate; end; end; procedure TformNotificacionesWindows.CrearAccesoDirectoConAppID; var RutaAccesoDirecto, RutaMenuInicio: string; ShellLink: IShellLinkW; PropStore: IPropertyStore; PersistFile: IPersistFile; PropVariant: TPropVariant; PathBuffer: array[0..MAX_PATH-1] of Char; begin if Succeeded(SHGetFolderPath(0, CSIDL_STARTMENU, 0, SHGFP_TYPE_CURRENT, @PathBuffer[0])) then RutaMenuInicio := PathBuffer else Exit; RutaAccesoDirecto := TPath.Combine(RutaMenuInicio, FConfig.AppDisplayName + '.lnk'); if FileExists(RutaAccesoDirecto) then Exit; CoInitialize(nil); try if Succeeded(CoCreateInstance(CLSID_ShellLink, nil, CLSCTX_INPROC_SERVER, IID_IShellLinkW, ShellLink)) then begin ShellLink.SetPath(PChar(Application.ExeName)); if (FConfig.IconoNotificacion <> '') and FileExists(FConfig.IconoNotificacion) then ShellLink.SetIconLocation(PChar(FConfig.IconoNotificacion), 0); if Succeeded(ShellLink.QueryInterface(IID_IPropertyStore, PropStore)) then begin OleCheck(InitPropVariantFromString(PChar(FConfig.AppID), PropVariant)); OleCheck(PropStore.SetValue(PKEY_AppUserModel_ID, PropVariant)); OleCheck(PropStore.Commit); PropVariantClear(PropVariant); end; if Succeeded(ShellLink.QueryInterface(IID_IPersistFile, PersistFile)) then PersistFile.Save(PWideChar(RutaAccesoDirecto), True); end; finally CoUninitialize; end; end; procedure TformNotificacionesWindows.EscribirLog(const Mensaje: string; EsError: Boolean = False); var ArchivoLog: TextFile; Prefijo: string; begin try if EsError then Prefijo := '[ERROR] ' else Prefijo := '[INFO] '; AssignFile(ArchivoLog, FRutaArchivoLog); try if FileExists(FRutaArchivoLog) then Append(ArchivoLog) else Rewrite(ArchivoLog); Writeln(ArchivoLog, Format('[%s] %s%s', [FormatDateTime('yyyy-mm-dd hh:nn:ss', Now), Prefijo, Mensaje])); finally CloseFile(ArchivoLog); end; except end; end; procedure TformNotificacionesWindows.MostrarNotificacionDesdeJSON; var ContenidoJSON: TStringList; DatosJSON: TJSONObject; Notificacion: TNotification; Titulo, Cuerpo, TipoNotificacion: string; begin ContenidoJSON := TStringList.Create; try ContenidoJSON.LoadFromFile(FRutaArchivoMensaje, TEncoding.UTF8); DatosJSON := TJSONObject.ParseJSONValue(ContenidoJSON.Text) as TJSONObject; if not Assigned(DatosJSON) then begin EscribirLog('El contenido del fichero de mensaje no es un JSON válido. Revise la sintaxis.', True); Exit; end; try Titulo := DatosJSON.GetValue<string>('titulo'); Cuerpo := DatosJSON.GetValue<string>('cuerpo'); if HaSidoMostradaRecientemente(Titulo, Cuerpo) then begin EscribirLog(Format('Notificación duplicada ("%s") dentro del límite de tiempo. No se mostrará.', [Titulo])); Exit; end; TipoNotificacion := DatosJSON.GetValue<string>('tipo_notificacion', 'normal'); if SameText(TipoNotificacion, 'powershell') then MostrarNotificacionPowerShell(Titulo, Cuerpo, DatosJSON) else begin Notificacion := CentroNotificaciones.CreateNotification; try Notificacion.Name := FConfig.AppID; Notificacion.Title := Titulo; Notificacion.AlertBody := StringReplace(Cuerpo, 'n', #13#10, [rfReplaceAll]); CentroNotificaciones.PresentNotification(Notificacion); finally Notificacion.Free; end; end; RegistrarNotificacionEnHistorial(Titulo, Cuerpo); EscribirLog('Notificación enviada para mostrar, de tipo: ' + TipoNotificacion + ' y asunto: ' + Titulo); finally DatosJSON.Free; end; finally ContenidoJSON.Free; end; end; procedure TformNotificacionesWindows.MostrarNotificacionPowerShell(const Titulo, Cuerpo: string; DatosJSON: TJSONObject); var ScriptPS, ToastTemplateXML, LaunchAttribute, DurationAttribute, AccionPrincipalXML, BotonCerrarXML, PieXML, HeroImageXML, InlineImageXML, LogoImageXML, CuerpoPS, RutaImagenLogo, RutaImagenArriba, RutaImagenInline, PieNotificacion, AccionPrincipal, ToastAttributes, ActionsXML: string; begin // --- PREPARACIÓN DE VARIABLES DE POWERSHELL --- RutaImagenLogo := DatosJSON.GetValue<string>('imagen_logo', ''); if (RutaImagenLogo <> '') and FileExists(RutaImagenLogo) then RutaImagenLogo := TPath.GetFullPath(RutaImagenLogo) else RutaImagenLogo := ''; RutaImagenArriba := DatosJSON.GetValue<string>('imagen_arriba', ''); if (RutaImagenArriba <> '') and FileExists(RutaImagenArriba) then RutaImagenArriba := TPath.GetFullPath(RutaImagenArriba) else RutaImagenArriba := ''; RutaImagenInline := DatosJSON.GetValue<string>('imagen_inline', ''); if (RutaImagenInline <> '') and FileExists(RutaImagenInline) then RutaImagenInline := TPath.GetFullPath(RutaImagenInline) else RutaImagenInline := ''; PieNotificacion := DatosJSON.GetValue<string>('pie_notificacion', ''); AccionPrincipal := DatosJSON.GetValue<string>('accion_principal', ''); // --- PREPARACIÓN DE FRAGMENTOS XML (O CADENAS VACÍAS SI NO APLICAN) --- LaunchAttribute := ''; if AccionPrincipal <> '' then LaunchAttribute := ' launch="$AccionPrincipal" activationType="protocol"'; if SameText(DatosJSON.GetValue<string>('duracion', 'corta'), 'larga') then DurationAttribute := ' duration="long"' else DurationAttribute := ''; LogoImageXML := ''; if RutaImagenLogo <> '' then LogoImageXML := '##LogoImageXML##'; HeroImageXML := ''; if RutaImagenArriba <> '' then HeroImageXML := '##HeroImageXML##'; InlineImageXML := ''; if RutaImagenInline <> '' then InlineImageXML := '##InlineImageXML##'; PieXML := ''; if PieNotificacion <> '' then PieXML := '##PieXML##'; AccionPrincipalXML := ''; if AccionPrincipal <> '' then AccionPrincipalXML := '<action content="Abrir" arguments="$AccionPrincipal" activationType="protocol"/>'; BotonCerrarXML := ''; if DatosJSON.GetValue<Boolean>('mostrar_boton_cerrar', False) then BotonCerrarXML := '<action content="Cerrar" arguments="dismiss" activationType="system"/>'; // --- LECTURA Y REEMPLAZO EN LA PLANTILLA --- ToastTemplateXML := TFile.ReadAllText(FConfig.RutaXmlTemplate); ToastAttributes := DurationAttribute + LaunchAttribute; if (AccionPrincipalXML <> '') or (BotonCerrarXML <> '') then ActionsXML := #13#10 + ' <actions>' + #13#10 + ' ' + AccionPrincipalXML + #13#10 + ' ' + BotonCerrarXML + #13#10 + ' </actions>' else ActionsXML := ''; ToastTemplateXML := StringReplace(ToastTemplateXML, '##ToastAttributes##', ToastAttributes, [rfReplaceAll]); ToastTemplateXML := StringReplace(ToastTemplateXML, '##LogoImageXML##', IfThen(LogoImageXML<>'', '<image placement="appLogoOverride" src="$ImagenLogo"/>', ''), [rfReplaceAll]); ToastTemplateXML := StringReplace(ToastTemplateXML, '##HeroImageXML##', IfThen(HeroImageXML<>'', '<image placement="hero" src="$ImagenArriba"/>', ''), [rfReplaceAll]); ToastTemplateXML := StringReplace(ToastTemplateXML, '##InlineImageXML##', IfThen(InlineImageXML<>'', '<image src="$ImagenInline"/>', ''), [rfReplaceAll]); ToastTemplateXML := StringReplace(ToastTemplateXML, '##PieXML##', IfThen(PieXML<>'', '<text placement="attribution">$PieNotificacion</text>', ''), [rfReplaceAll]); ToastTemplateXML := StringReplace(ToastTemplateXML, '##ActionsXML##', ActionsXML, [rfReplaceAll]); // --- CONSTRUCCIÓN DEL SCRIPT DE POWERSHELL --- CuerpoPS := StringReplace(StringReplace(Cuerpo, 'n', '`n', [rfReplaceAll]), '"', '`"', [rfReplaceAll]); ScriptPS := '$Titulo = ''' + Titulo.Replace('''', '''''') + ''';' + #13#10 + '$Cuerpo = "' + CuerpoPS + '";' + #13#10 + '$ImagenLogo = ''' + RutaImagenLogo.Replace('''', '''''') + ''';' + #13#10 + '$ImagenArriba = ''' + RutaImagenArriba.Replace('''', '''''') + ''';' + #13#10 + '$ImagenInline = ''' + RutaImagenInline.Replace('''', '''''') + ''';' + #13#10 + '$PieNotificacion = ''' + PieNotificacion.Replace('''', '''''') + ''';' + #13#10 + '$AccionPrincipal = ''' + AccionPrincipal.Replace('''', '''''') + ''';' + #13#10 + '$AppId = ''' + FConfig.AppID + ''';' + #13#10 + '$ToastTemplate = @"' + #13#10 + ToastTemplateXML + #13#10 + '"@' + #13#10 + '[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null;' + #13#10 + '[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null;' + #13#10 + '$ToastXml = New-Object Windows.Data.Xml.Dom.XmlDocument;' + #13#10 + '$ToastXml.LoadXml($ToastTemplate);' + #13#10 + '$Toast = [Windows.UI.Notifications.ToastNotification]::new($ToastXml);' + #13#10 + '[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($AppId).Show($Toast);'; EjecutarComandoPowershell(ScriptPS); end; procedure TformNotificacionesWindows.EjecutarComandoPowershell(const Script: string); var ComandoBase64, ComandoCompleto: string; SI: TStartupInfo; PI: TProcessInformation; begin ComandoBase64 := TNetEncoding.Base64.EncodeBytesToString(TEncoding.Unicode.GetBytes(Script)); ComandoCompleto := 'powershell.exe -NoProfile -ExecutionPolicy Bypass -EncodedCommand ' + ComandoBase64; EscribirLog('Ejecutando PowerShell para mostrar notificación...'); ZeroMemory(@SI, SizeOf(SI)); SI.cb := SizeOf(SI); SI.dwFlags := STARTF_USESHOWWINDOW; SI.wShowWindow := SW_HIDE; ZeroMemory(@PI, SizeOf(PI)); if not CreateProcess(nil, PChar(ComandoCompleto), nil, nil, False, CREATE_NO_WINDOW, nil, nil, SI, PI) then begin EscribirLog('Error al ejecutar PowerShell: ' + SysErrorMessage(GetLastError), True); Exit; end; try WaitForSingleObject(PI.hProcess, 5000); finally CloseHandle(PI.hProcess); CloseHandle(PI.hThread); end; end; function TformNotificacionesWindows.HaSidoMostradaRecientemente(const ATitulo, ACuerpo: string): Boolean; var Historial: TJSONArray; Item: TJSONValue; FechaNotificacion: TDateTime; FS: TFormatSettings; begin Result := False; if not FileExists(FRutaArchivoHistorial) then Exit; FS := TFormatSettings.Create; FS.ShortDateFormat := 'yyyy-mm-dd'; FS.DateSeparator := '-'; FS.TimeSeparator := ':'; Historial := nil; try Historial := TJSONObject.ParseJSONValue(TFile.ReadAllText(FRutaArchivoHistorial)) as TJSONArray; if not Assigned(Historial) then Exit; for Item in Historial do begin if (Item is TJSONObject) and SameText((Item as TJSONObject).GetValue<string>('titulo', ''), ATitulo) and SameText((Item as TJSONObject).GetValue<string>('cuerpo', ''), ACuerpo) then begin if TryStrToDateTime((Item as TJSONObject).GetValue<string>('fecha', ''), FechaNotificacion, FS) then begin if MinutesBetween(Now, FechaNotificacion) <= FConfig.MinutosLimiteDuplicados then begin Result := True; Exit; end; end; end; end; finally if Assigned(Historial) then Historial.Free; end; end; procedure TformNotificacionesWindows.RegistrarNotificacionEnHistorial(const ATitulo, ACuerpo: string); var Historial: TJSONArray; NuevaNotificacion: TJSONObject; begin Historial := nil; try if FileExists(FRutaArchivoHistorial) then Historial := TJSONObject.ParseJSONValue(TFile.ReadAllText(FRutaArchivoHistorial)) as TJSONArray; if not Assigned(Historial) then Historial := TJSONArray.Create; NuevaNotificacion := TJSONObject.Create; NuevaNotificacion.AddPair('titulo', ATitulo); NuevaNotificacion.AddPair('cuerpo', ACuerpo); NuevaNotificacion.AddPair('fecha', FormatDateTime('yyyy-mm-dd hh:nn:ss', Now)); Historial.AddElement(NuevaNotificacion); TFile.WriteAllText(FRutaArchivoHistorial, Historial.ToString); finally if Assigned(Historial) then Historial.Free; end; end; end. |
Ejemplo en C# para ejecutar aplicación de notificaciones
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
using System.Diagnostics; // Necesario para Process y ProcessStartInfo using System.IO; // Necesario para Path y File using System.Text.Json; // Necesario para la serialización de JSON /// <summary> /// Envía una notificación de forma silenciosa ejecutando NotificacionesWindows.exe. /// </summary> /// <param name="titulo">El título de la notificación.</param> /// <param name="cuerpo">El cuerpo del mensaje. Puede contener n para saltos de línea.</param> public void EnviarNotificacionSilenciosa(string titulo, string cuerpo) { // 1. Definir la ruta al ejecutable (asume que está en la misma carpeta). string exePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NotificacionesWindows.exe"); if (!File.Exists(exePath)) { // Manejar el error: el notificador no se encontró. Console.WriteLine("Error: No se encontró Notificacion.exe"); return; } string tempJsonPath = null; try { // 2. Crear un objeto anónimo con los datos de la notificación. var notificacionData = new { titulo = titulo, cuerpo = cuerpo, tipo_notificacion = "powershell", // Usar siempre powershell para más opciones duracion = "larga", mostrar_boton_cerrar = true // Aquí podrías añadir más parámetros como "imagen_logo", "accion_principal", etc. }; // 3. Crear un fichero JSON temporal para pasar los datos. tempJsonPath = Path.GetTempFileName(); File.WriteAllText(tempJsonPath, JsonSerializer.Serialize(notificacionData)); // 4. Configurar el proceso para una ejecución silenciosa. var startInfo = new ProcessStartInfo { FileName = exePath, Arguments = $""{tempJsonPath}"", // Poner la ruta entre comillas por si tiene espacios. // --- Claves para la ejecución silenciosa --- UseShellExecute = false, // Imprescindible para controlar la ventana. CreateNoWindow = true, // No crear una ventana de consola. WindowStyle = ProcessWindowStyle.Hidden // Asegurarse de que esté oculta si se crea. }; // 5. Iniciar el proceso y no esperar a que termine ("disparar y olvidar"). // Esto evita que nuestra aplicación principal se congele. Process.Start(startInfo); } catch (Exception ex) { // Registrar el error en el log de la aplicación C#. Console.WriteLine($"Error al enviar la notificación: {ex.Message}"); } finally { // 6. Limpiar: asegurarse de que el fichero temporal se borre siempre. if (tempJsonPath != null && File.Exists(tempJsonPath)) { File.Delete(tempJsonPath); } } } |