Share via


Função NetAlertRaiseEx (lmalert.h)

[Não há suporte para essa função a partir do Windows Vista porque não há suporte para o serviço de alerta.]

A função NetAlertRaiseEx notifica todos os clientes registrados quando ocorre um evento específico. Você pode chamar essa função estendida para simplificar o envio de uma mensagem de alerta porque NetAlertRaiseEx não exige que você especifique uma estrutura STD_ALERT .

Sintaxe

NET_API_STATUS NET_API_FUNCTION NetAlertRaiseEx(
  [in] LPCWSTR AlertType,
  [in] LPVOID  VariableInfo,
  [in] DWORD   VariableInfoSize,
  [in] LPCWSTR ServiceName
);

Parâmetros

[in] AlertType

Um ponteiro para uma cadeia de caracteres constante que especifica a classe de alerta (tipo de alerta) a ser gerada. Esse parâmetro pode ser um dos seguintes valores predefinidos ou uma classe de alerta definida pelo usuário para aplicativos de rede. (O nome do evento de um alerta pode ser qualquer cadeia de texto.)

Nome Significado
ALERT_ADMIN_EVENT
A intervenção de um administrador é necessária.
ALERT_ERRORLOG_EVENT
Uma entrada foi adicionada ao log de erros.
ALERT_MESSAGE_EVENT
Um usuário ou aplicativo recebeu uma mensagem de difusão.
ALERT_PRINT_EVENT
Um trabalho de impressão foi concluído ou ocorreu um erro de impressão.
ALERT_USER_EVENT
Um aplicativo ou recurso foi usado.

[in] VariableInfo

Um ponteiro para os dados a serem enviados aos clientes que escutam a mensagem de interrupção. Os dados devem consistir em uma estrutura ADMIN_OTHER_INFO, ERRLOG_OTHER_INFO, PRINT_OTHER_INFO ou USER_OTHER_INFO seguida por qualquer informação de comprimento variável necessária. Para obter mais informações, consulte o exemplo de código na seção Comentários a seguir.

O aplicativo de chamada deve alocar e liberar a memória para todas as estruturas e dados variáveis. Para obter mais informações, consulte Buffers de função de gerenciamento de rede.

[in] VariableInfoSize

O número de bytes de informações de variáveis no buffer apontado pelo parâmetro VariableInfo .

[in] ServiceName

Um ponteiro para uma cadeia de caracteres constante que especifica o nome do serviço que gera a mensagem de interrupção.

Valor retornado

Se a função for bem-sucedida, o valor retornado será NERR_Success.

Se a função falhar, o valor retornado será um código de erro do sistema e um poderá ser um dos códigos de erro a seguir. Para obter uma lista de todos os códigos de erro possíveis, consulte Códigos de erro do sistema.

Código de retorno Descrição
ERROR_INVALID_PARAMETER
Um parâmetro está incorreto. Esse erro será retornado se o parâmetro AlertEventName for NULL ou uma cadeia de caracteres vazia, o parâmetro ServiceName for NULL ou uma cadeia de caracteres vazia, o parâmetro VariableInfo for NULL ou o parâmetro VariableInfoSize for maior que 512 menos o tamanho da estrutura STD_ALERT .
ERROR_NOT_SUPPORTED
A solicitação não terá suporte. Esse erro é retornado no Windows Vista e posteriormente, pois não há suporte para o serviço Alerter.

Comentários

Nenhuma associação de grupo especial é necessária para executar com êxito a função NetAlertRaiseEx .

O serviço de alerta deve estar em execução no computador cliente quando você chama a função NetAlertRaiseEx ou a função falha com ERROR_FILE_NOT_FOUND.

Exemplos

O exemplo de código a seguir demonstra como gerar os seguintes tipos de mensagens de interrupção (alertas) chamando a função NetAlertRaiseEx :

Em cada instância, o código atribui valores aos membros da estrutura de informações de alerta relevante. Depois disso, o exemplo recupera um ponteiro para a parte do buffer de mensagens que segue a estrutura chamando a macro ALERT_VAR_DATA . O código também preenche as cadeias de caracteres de comprimento variável nesta parte do buffer. Por fim, o exemplo chama NetAlertRaiseEx para enviar o alerta.

Observe que o aplicativo de chamada deve alocar e liberar a memória para todas as estruturas e dados de comprimento variável em um buffer de mensagens de alerta.

Para passar uma estrutura definida pelo usuário e cadeias de caracteres válidas em um alerta de usuário, você deve criar um arquivo de mensagem de evento e vinculá-lo ao seu aplicativo. Você também deve registrar o aplicativo na subchave EventMessageFile na seção EventLog do registro. Se você não registrar o aplicativo, o alerta do usuário conterá as informações passadas nas cadeias de caracteres de comprimento variável que seguem a estrutura USER_OTHER_INFO . Para obter mais informações sobre EventMessageFile, consulte Log de Eventos.

#ifndef UNICODE
#define UNICODE
#endif

#pragma comment(lib, "netapi32.lib")

#include <windows.h>
#include <lm.h>
#include <stdio.h>
#include <time.h>
//
// Define default strings.
//
#define PROGRAM_NAME    TEXT("NETALRT")
#define szComputerName  TEXT("\\\\TESTCOMPUTER")
#define szUserName      TEXT("TEST")
#define szQueueName     TEXT("PQUEUE")
#define szDestName      TEXT("MYPRINTER")
#define szStatus        TEXT("OK")
//
// Define structure sizes.
//
#define VAREDSIZE 312  // maximum size of the variable length message
char buff[VAREDSIZE];
//
int main()
{
   time_t             now;
   PADMIN_OTHER_INFO  pAdminInfo; // ADMIN_OTHER_INFO structure
   PPRINT_OTHER_INFO  pPrintInfo; // PRINT_OTHER_INFO structure
   PUSER_OTHER_INFO   pUserInfo;  // USER_OTHER_INFO structure
   TCHAR              *p;
   DWORD dwResult; 

   time( &now );  // Retrieve the current time to print it later.

   //
   // Sending an administrative alert 
   //
   // Assign values to the members of the ADMIN_OTHER_INFO structure.
   //
   pAdminInfo = (PADMIN_OTHER_INFO) buff; 
   ZeroMemory(pAdminInfo, VAREDSIZE);
   //
   // Error 2377, NERR_LogOverflow, indicates
   //  a log file is full.
   //
   pAdminInfo->alrtad_errcode = 2377;
   pAdminInfo->alrtad_numstrings = 1;
   //
   // Retrieve a pointer to the variable data portion at the 
   //  end of the buffer by calling the ALERT_VAR_DATA macro.
   //
   p = (LPTSTR) ALERT_VAR_DATA(pAdminInfo); 
   //
   // Fill in the variable-length, concatenated strings 
   //  that follow the ADMIN_OTHER_INFO structure. These strings
   //  will be written to the message log.
   //
   wcscpy_s(p,VAREDSIZE/2, TEXT("'C:\\MYLOG.TXT'")); 
   //
   // Call the NetAlertRaiseEx function to raise the
   //  administrative alert.
   //
   dwResult = NetAlertRaiseEx(ALERT_ADMIN_EVENT, pAdminInfo, 255 , TEXT("MYSERVICE"));
   //
   // Display the results of the function call.
   //
   if (dwResult != NERR_Success)
   {
      wprintf(L"NetAlertRaiseEx failed: %d\n", dwResult);
      return -1;
   }
   else
      wprintf(L"Administrative alert raised successfully.\n");


   //
   // Sending a print alert
   //
   // Assign values to the members of the PRINT_OTHER_INFO structure.
   //
   pPrintInfo = (PPRINT_OTHER_INFO) buff; 
   ZeroMemory(pPrintInfo, VAREDSIZE);        
   pPrintInfo->alrtpr_jobid = 5457;
   pPrintInfo->alrtpr_status = 0;
   pPrintInfo->alrtpr_submitted = (DWORD) now;
   pPrintInfo->alrtpr_size = 1000;
   //
   // Retrieve a pointer to the variable data portion at the 
   //  end of the buffer by calling the ALERT_VAR_DATA macro. 
   //
   p = (LPTSTR) ALERT_VAR_DATA(pPrintInfo);  
   //
   // Fill in the variable-length, concatenated strings 
   //  that follow the PRINT_OTHER_INFO structure. 
   //
   wcscpy_s(p, VAREDSIZE/2, szComputerName); // computername 
   p += lstrlen(p) + 1;
   wcscpy_s(p, (VAREDSIZE/2)-wcslen(szComputerName)-1, szUserName);     // user name
   p += lstrlen(p) + 1;
   wcscpy_s(p, (VAREDSIZE/2)-wcslen(szComputerName)-wcslen(szUserName)-2, 
       szQueueName);    // printer queuename
   p += lstrlen(p) + 1;
   wcscpy_s(p, (VAREDSIZE/2)-wcslen(szComputerName)-wcslen(szUserName)-wcslen(szQueueName)-3,
       szDestName);     // destination or printer name (optional)
   p += lstrlen(p) + 1;
   wcscpy_s(p, (VAREDSIZE/2)-wcslen(szComputerName)-wcslen(szUserName)-wcslen(szQueueName) 
       - wcslen(szDestName)-4, szStatus);       // status of the print job (optional)
   //
   // Call the NetAlertRaiseEx function to raise the
   //  print alert.
   //
   dwResult = NetAlertRaiseEx(ALERT_PRINT_EVENT, pPrintInfo, VAREDSIZE, TEXT("MYSERVICE"));
   //
   // Display the results of the function call.
   //
   if (dwResult != NERR_Success)
   {
      wprintf(L"NetAlertRaiseEx failed: %d\n", dwResult);
      return -1;
   }
   else
      wprintf(L"Print alert raised successfully.\n");


   //
   // Sending a user alert
   //
   // Assign values to the members of the USER_OTHER_INFO structure.
   //
   pUserInfo  = (PUSER_OTHER_INFO)  buff; 
   ZeroMemory(pUserInfo, VAREDSIZE);
   pUserInfo->alrtus_errcode = 0xffff;
   pUserInfo->alrtus_numstrings = 1;
   //
   // Retrieve a pointer to the variable data portion at the 
   //  end of the buffer by calling the ALERT_VAR_DATA macro.
   //
   p = (LPTSTR) ALERT_VAR_DATA(pUserInfo); 
   //
   // Fill in the variable-length, concatenated strings 
   //  that follow the USER_OTHER_INFO structure.
   //
   wcscpy_s(p,(VAREDSIZE/2), TEXT("C:\\USERLOG.TXT"));
   p += lstrlen(p) + 1;
   wcscpy_s(p, (VAREDSIZE/2) - wcslen(TEXT("C:\\USERLOG.TXT"))-1, szUserName);
   //
   // Call the NetAlertRaiseEx function to raise the
   //  user alert.
   //
   dwResult = NetAlertRaiseEx(ALERT_USER_EVENT, pUserInfo, VAREDSIZE, TEXT("MYSERVICE"));
   //
   // Display the results of the function call.
   //
   if (dwResult != NERR_Success)
   {
      wprintf(L"NetAlertRaiseEx failed: %d\n", dwResult);
      return -1;
   }
   else
      wprintf(L"User alert raised successfully.\n");

   return(dwResult);   
}

Requisitos

   
Cliente mínimo com suporte Windows 2000 Professional [somente aplicativos da área de trabalho]
Servidor mínimo com suporte Windows 2000 Server [somente aplicativos da área de trabalho]
Plataforma de Destino Windows
Cabeçalho lmalert.h (inclua Lm.h)
Biblioteca Netapi32.lib
DLL Netapi32.dll

Confira também

ADMIN_OTHER_INFO

ALERT_VAR_DATA

Funções de alerta

ERRLOG_OTHER_INFO

NetAlertRaise

Funções de gerenciamento de rede

Visão geral do gerenciamento de rede

PRINT_OTHER_INFO

USER_OTHER_INFO