Page 1 of 1

NetMessageBufferSend

Posted: March 3rd, 2004, 11:36 pm
by ccb056
anyone know how to use NetMessageBufferSend

is it for vb or c++ or both?

I found some code

Code: Select all

Imports Microsoft.VisualBasic
Imports System
Imports System.IO
Imports System.Runtime.Remoting.Messaging

Namespace PAB.Util
Public Class NETSender
Public Delegate Function SendMessageDelegate(ByVal Dest As String, ByVal Message As String) As Integer


Public Function SendMessage(ByVal strDestination As String, ByVal strMessage As String) As Integer
Dim str2 As String
Try
Dim str1 As String = String.Concat(New String() {"net send ", strDestination, " ", strMessage, " > C:\sendResult.log"})
Dim fileStream1 As FileStream = New FileStream("c:\NetSender.bat", FileMode.Create, FileAccess.Write)
Dim streamWriter As streamWriter = New streamWriter(fileStream1)
streamWriter.BaseStream.Seek(CLng(0), SeekOrigin.End)
streamWriter.Write(str1)
streamWriter.Flush()
streamWriter.Close()
fileStream1.Close()
Dim process As process = New process
process.StartInfo.FileName = "C:\NetSender.bat"
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
process.Start()
process.WaitForExit()
process.Close()
Dim fileStream2 As FileStream = New FileStream("C:\sendResult.log", FileMode.Open, FileAccess.Read)
Dim streamReader As streamReader = New streamReader(fileStream2)
streamReader.BaseStream.Seek(CLng(0), SeekOrigin.Begin)
str2 = streamReader.ReadLine()
streamReader.Close()
fileStream2.Close()

If str2.IndexOf("successfully sent") > -1 Then

Return 1
Else
Return 9
End If

Catch e As Exception
Return 9
End Try
End Function

Public Sub GetResultsOnCallback(ByVal ar As IAsyncResult)
Dim res As Integer
Dim SendMessageDelegate As SendMessageDelegate = CType(CType(ar, AsyncResult).AsyncDelegate, SendMessageDelegate)
Try
res = SendMessageDelegate.EndInvoke(ar)
Catch e As Exception
End Try
End Sub

Public Function SendMessageAsync(ByVal Destination As String, ByVal Message As String) As String
Dim SendMessageDelegate As SendMessageDelegate = AddressOf Me.SendMessage
Dim asyncCallback As asyncCallback = AddressOf Me.GetResultsOnCallback
SendMessageDelegate.BeginInvoke(Destination, Message, asyncCallback, Nothing)
Return "ok"
End Function

End Class
End Namespace


N.B.  - Oops! I spoke too soon.  Got the API working now, in C#:

using System;
using System.Runtime.InteropServices;
namespace PAB.Util
{
public class NetSend
{
public NetSend()
{
}
public int netSend(string sFrom, string sTo, string sMessage)
{
byte [] bBuffer = System.Text.Encoding.Unicode.GetBytes(sMessage);
int nRet = NetMessageBufferSend(null, sTo, null, sMessage, sMessage.Length *
2 + 2);
return nRet;
}

[DllImport ("Netapi32", CharSet=CharSet.Unicode)]
public static extern int NetMessageBufferSend(
string servername,
string msgname,
string fromname,
string buf,
int buflen);
}
}



And again, in VB.NET:

Imports Microsoft.VisualBasic
Imports System
Imports System.Runtime.InteropServices
Imports System.Text

Namespace PAB.Util
    Public Class NetSend

        Public Function netSend(sFrom As String, sTo As String, sMessage As String) As Integer
            Dim bBuffer As Byte() = Encoding.Unicode.GetBytes(sMessage)
            Return NetMessageBufferSend(Nothing, sTo, Nothing, sMessage, sMessage.Length * 2 + 2)
        End Function

        <DllImportAttribute("Netapi32", CharSet:=CharSet.Unicode)> _
        Public Shared Function NetMessageBufferSend(servername As String, msgname As String, fromname As String, buf As String, buflen As Integer) As Integer
        End Function
    End Class
End Namespace 

and

Code: Select all

VERSION 4.00
Begin VB.Form Form1 
   Caption         =   "VB Solutions - Send Net Message"
   ClientHeight    =   3825
   ClientLeft      =   2940
   ClientTop       =   2325
   ClientWidth     =   7275
   Height          =   4230
   Icon            =   "FormSend.frx":0000
   Left            =   2880
   LinkTopic       =   "Form1"
   ScaleHeight     =   3825
   ScaleWidth      =   7275
   Top             =   1980
   Width           =   7395
   Begin VB.Frame Frame1 
      Height          =   3255
      Left            =   120
      TabIndex        =   0
      Top             =   0
      Width           =   6975
      Begin VB.ComboBox Combo1 
         Height          =   315
         Left            =   600
         TabIndex        =   5
         Top             =   360
         Width           =   2415
      End
      Begin VB.CommandButton Command_Send 
         Caption         =   "Send"
         Height          =   375
         Left            =   4920
         TabIndex        =   2
         Top             =   360
         Width           =   1695
      End
      Begin VB.TextBox Text_Message 
         Height          =   2055
         Left            =   240
         MultiLine       =   -1  'True
         TabIndex        =   1
         Top             =   960
         Width           =   6375
      End
      Begin VB.Label Label2 
         Caption         =   "To:"
         Height          =   255
         Left            =   240
         TabIndex        =   4
         Top             =   360
         Width           =   495
      End
      Begin VB.Label Label1 
         Caption         =   "Label1"
         Height          =   255
         Left            =   480
         TabIndex        =   3
         Top             =   360
         Width           =   15
      End
   End
   Begin VB.Label Label_Feedback 
      BorderStyle     =   1  'Fixed Single
      Height          =   375
      Left            =   120
      TabIndex        =   6
      Top             =   3360
      Width           =   6975
   End
End
Attribute VB_Name = "Form1"
Attribute VB_Creatable = False
Attribute VB_Exposed = False

Private Sub Command_Send_Click()
   
    Dim lReturnCode As Long
    Dim sUnicodeToName As String
    Dim sUnicodeFromName As String
    Dim sUnicodeMessage As String
    Dim lMessageLength As Long
     
    'Get the local computer name and convert it to unicode
    sUnicodeFromName = StrConv(GetLocalSystemName, vbUnicode)
    
    ' Convert the to computer name to Unicode
    sUnicodeToName = StrConv(Combo1.Text, vbUnicode)
   
   ' Convert the message text to unicode
    sUnicodeMessage = StrConv(Text_Message.Text, vbUnicode)
   
    lMessageLength = Len(sUnicodeMessage)

    ' Hourglass pointer
    MousePointer = vbHourglass
    Label_feedback.Caption = vbNullString

    ' Send the message
    lReturnCode = NetMessageBufferSend("", _
                                        sUnicodeToName, _
                                        sUnicodeFromName, _
                                        sUnicodeMessage, _
                                        lMessageLength)
    
    ' Prove some feedback about the send action
    If lReturnCode = 0 Then
        Text_Message.Text = vbNullString
        Label_feedback.Caption = "Message was successfully sent"
    Else
        Label_feedback.Caption = "Error - Return code: " & CStr(lReturnCode)
    End If
    
     ' Default pointer
    MousePointer = vbDefault
    
End Sub

Private Sub Form_Load()

    Dim colServerNames As New Collection
    
    Set colServerNames = GetNetworkSystemNames(SERVER_TYPE_NT)
    
    For Num = 1 To colServerNames.Count
        Combo1.AddItem colServerNames.Item(Num)
    Next
    
    Combo1.AddItem GetDomainName & "*"
    
End Sub

Posted: March 4th, 2004, 12:13 am
by Tebow2000
hrmm... If that is the exact code.. Cant you make it into an .exe file and execute it?

Posted: May 6th, 2004, 11:15 pm
by ccb056
I found another code for NetMessageBufferSend
Sending a message from one machine to another, with the message source originating on a NT system, can be easily done using the NetMessageBufferSend API. This is essentially the same as using the DOS command NET SEND. The receiving system will display the message appropriately; when sent to another NT system, the Net Message dialog will pop on screen. When sending to a Windows9x system, the message will be delivered through the WinPopup utility (which must be running).
By varying the SendTo, SendFrom and Server members of the call, the alert can be broadcast to specific users or to your own system.
Start a new project with four text boxes (Text1-Text4 (Text4 can be multiline)), a command button (Command1) and a label (Label1) to display the returned message. Other ID labels for the form are optional. Add the following to the form:

Code: Select all

'--------------------------------------------------------------
' Copyright ©1996-2004 VBnet, Randy Birch, All Rights Reserved.
'   Terms of use http://vbnet.mvps.org/terms/pages/terms.htm   
'--------------------------------------------------------------

'from LMMSG.H
Private Const ERROR_ACCESS_DENIED As Long = 5
Private Const ERROR_BAD_NETPATH As Long = 53
Private Const ERROR_INVALID_PARAMETER As Long = 87
Private Const ERROR_NOT_SUPPORTED As Long = 50
Private Const ERROR_INVALID_NAME As Long = 123
Private Const NERR_BASE As Long = 2100
Private Const NERR_SUCCESS As Long = 0                     
Private Const NERR_NetworkError As Long = (NERR_BASE + 36) 
Private Const NERR_NameNotFound As Long = (NERR_BASE + 173)
Private Const NERR_UseNotFound As Long = (NERR_BASE + 150) 

Private Const MAX_COMPUTERNAME As Long = 15
Private Const VER_PLATFORM_WIN32s As Long = 0
Private Const VER_PLATFORM_WIN32_WINDOWS As Long = 1
Private Const VER_PLATFORM_WIN32_NT As Long = 2

Private Type OSVERSIONINFO
  OSVSize         As Long
  dwVerMajor      As Long
  dwVerMinor      As Long
  dwBuildNumber   As Long
  PlatformID      As Long
  szCSDVersion    As String * 128 
End Type

'User-defined type for passing
'the data to the Send function
Private Type NetMessageData
   sServerName As String
   sSendTo As String
   sSendFrom As String
   sMessage As String
End Type

'NetMessageBufferSend parameters:
'servername:  Unicode string specifying the name of the
'             remote server on which the function is to
'             execute. If this parameter is vbNullString,
'             the local computer is used. 
'
'msgname:     Unicode string specifying the message alias to
'             which the message buffer should be sent. 
'
'fromname:    Unicode string specifying who the message is from. 
'             This parameter is required to send interrupting messages
'             from the computer name. If this parameter is NULL, the
'             message is sent from the logged-on user.
'
'msgbuf:      Unicode string containing the message to send.
'
'msgbuflen:   value that contains the length, in bytes, of
'             the message text pointed to by the msgbuf parameter.
Private Declare Function NetMessageBufferSend Lib "netapi32" _
  (ByVal servername As String, _
   ByVal msgname As String, _
   ByVal fromname As String, _
   ByVal msgbuf As String, _
   ByRef msgbuflen As Long) As Long

Private Declare Function GetComputerName Lib "kernel32" _
   Alias "GetComputerNameA" _
  (ByVal lpBuffer As String, _
   nSize As Long) As Long

Private Declare Function GetVersionEx Lib "kernel32" _
   Alias "GetVersionExA" _
  (lpVersionInformation As OSVERSIONINFO) As Long


Private Sub Form_Load()

   Dim tmp As String
   
  'pre-load the text boxes with
  'the local computer name for testing
   tmp = Space$(MAX_COMPUTERNAME + 1)
   Call GetComputerName(tmp, Len(tmp))
   
   Text1.Text = TrimNull(tmp)
   Text2.Text = TrimNull(tmp)
   Text3.Text = TrimNull(tmp)
   
End Sub


Private Sub Command1_Click()

   Dim MsgData As NetMessageData
   Dim sSuccess As String
   
   With MsgData
      .sServerName = Text1.Text
      .sSendTo = Text2.Text
      .sSendFrom = Text3.Text
      .sMessage = Text4.Text
   End With
   
    sSuccess = NetSendMessage(MsgData)
    
    Label1.Caption = sSuccess
    
End Sub


Private Function IsWinNT() As Boolean

  'returns True if running WinNT/Win2000/WinXP
   #If Win32 Then
  
      Dim OSV As OSVERSIONINFO
   
      OSV.OSVSize = Len(OSV)
   
      If GetVersionEx(OSV) = 1 Then
   
        'PlatformId contains a value representing the OS.
         IsWinNT = (OSV.PlatformID = VER_PLATFORM_WIN32_NT)
         
      End If

   #End If

End Function


Private Function NetSendMessage(msgData As NetMessageData) As String

   Dim success As Long
   
  'assure that the OS is NT ..
  'NetMessageBufferSend  can not
  'be called on Win9x
   If IsWinNT() Then
      
      With msgData
      
        'if To name omitted return error and exit
         If .sSendTo = "" Then
            
            NetSendMessage = GetNetSendMessageStatus(ERROR_INVALID_PARAMETER)
            Exit Function
            
         Else
       
           'if there is a message
            If Len(.sMessage) Then
   
              'convert the strings to unicode
               .sSendTo = StrConv(.sSendTo, vbUnicode)
               .sMessage = StrConv(.sMessage, vbUnicode)
            
              'Note that the API could be called passing
              'vbNullString as the SendFrom and sServerName
              'strings. This would generate the message on
              'the sending machine.
               If Len(.sServerName) > 0 Then
                     .sServerName = StrConv(.sServerName, vbUnicode)
               Else: .sServerName = vbNullString
               End If
                        
               If Len(.sSendFrom) > 0 Then
                     .sSendFrom = StrConv(.sSendFrom, vbUnicode)
               Else: .sSendFrom = vbNullString
               End If
            
              'change the cursor and show. Control won't return
              'until the call has completed.
               Screen.MousePointer = vbHourglass
           
               success = NetMessageBufferSend(.sServerName, _
                                              .sSendTo, _
                                              .sSendFrom, _
                                              .sMessage, _
                                              ByVal Len(.sMessage))
           
               Screen.MousePointer = vbNormal
           
               NetSendMessage = GetNetSendMessageStatus(success)
   
            End If 'If Len(.sMessage)
         End If  'If .sSendTo
      End With  'With msgData
   End If  'If IsWinNT
   
End Function


Private Function GetNetSendMessageStatus(nError As Long) As String
    
   Dim msg As String
   
   Select Case nError
   
     Case NERR_SUCCESS:            msg = "The message was successfully sent"
     Case NERR_NameNotFound:       msg = "Send To not found"
     Case NERR_NetworkError:       msg = "General network error occurred"
     Case NERR_UseNotFound:        msg = "Network connection not found"
     Case ERROR_ACCESS_DENIED:     msg = "Access to computer denied"
     Case ERROR_BAD_NETPATH:       msg = "Sent From server name not found."
     Case ERROR_INVALID_PARAMETER: msg = "Invalid parameter(s) specified."
     Case ERROR_NOT_SUPPORTED:     msg = "Network request not supported."
     Case ERROR_INVALID_NAME:      msg = "Illegal character or malformed name."
     Case Else:                    msg = "Unknown error executing command."
     
   End Select
   
   GetNetSendMessageStatus = msg
   
End Function
         

Private Function TrimNull(item As String)

  'return string before the terminating null
   Dim pos As Integer
   
   pos = InStr(item, Chr$(0))
   
   If pos Then
         TrimNull = Left$(item, pos - 1)
   Else: TrimNull = item
   End If
   
End Function