CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 18
  1. #1
    Join Date
    Oct 2007
    Posts
    84

    get computer name

    hi,
    i want to get the computer name of incoming print to my printer in a network.

    anyone knows how to do it?

    thanks

  2. #2
    Join Date
    Aug 1999
    Location
    <Classified>
    Posts
    6,882

    Re: get computer name

    You could use EnumJobs Win32 API to do this, you will get a JOB_INFO structure which has all the details of that job, like user, machine which created this job etc.

    Here is a sample on MSDN.
    Regards,
    Ramkrishna Pawar

  3. #3
    Join Date
    Oct 2007
    Posts
    84

    Re: get computer name

    thanks

    btw i already made a printer disable/enable apps, all i need is to check the computername of any client who is trying to print in my printer. i checked your link and its VB.Net and not csharp.net.
    my app is in csharp.net

    tia
    Last edited by homer.favenir; December 16th, 2009 at 02:57 AM.

  4. #4
    Join Date
    Aug 1999
    Location
    <Classified>
    Posts
    6,882

    Re: get computer name

    So, read the code and create C# equivalent, they just have few differences only, if you can't understand then post that piece of code and ask.
    Regards,
    Ramkrishna Pawar

  5. #5
    Join Date
    Oct 2007
    Posts
    84

    Re: get computer name

    its too long, and i only want is the machine name of the client.

  6. #6
    Join Date
    Aug 1999
    Location
    <Classified>
    Posts
    6,882

    Re: get computer name

    Then do it yourself, you need to Open Handle to the printer and then call EnumJobs on it, you will have to do a p/invoke thing.

    If that's too hard then there is no way by which I can help.
    Regards,
    Ramkrishna Pawar

  7. #7
    Join Date
    Oct 2008
    Location
    Cologne, Germany
    Posts
    756

    Re: get computer name

    maybe this will help you http://www.tech-archive.net/Archive/...4-04/4001.html
    almost exacly what you need
    win7 x86, VS 2008 & 2010, C++/CLI, C#, .NET 3.5 & 4.0, VB.NET, VBA... WPF is comming

    remeber to give feedback you think my response deserves recognition? perhaps you may want to click the Rate this post link/button and add to my reputation

    private lessons are not an option so please don't ask for help in private, I won't replay

    if you use Opera and you'd like to have the tab-button functionality for the texteditor take a look at my Opera Tab-UserScirpt; and if you know how to stop firefox from jumping to the next control when you hit tab let me know

  8. #8
    Join Date
    Oct 2007
    Posts
    84

    Re: get computer name

    Quote Originally Posted by Krishnaa View Post
    You could use EnumJobs Win32 API to do this, you will get a JOB_INFO structure which has all the details of that job, like user, machine which created this job etc.

    Here is a sample on MSDN.
    hi,
    i have an error in
    Code:
     'Form overrides dispose to clean up the component list.
        <System.Diagnostics.DebuggerNonUserCode()> _
        Protected Overrides Sub Dispose(ByVal disposing As Boolean)
            Try
                If disposing AndAlso components IsNot Nothing Then
                    components.Dispose()
                End If
            Finally
                MyBase.Dispose(disposing)
            End Try
        End Sub
    the error is
    Code:
    Error	1	'Protected Overrides Sub Dispose(disposing As Boolean)' has multiple definitions with identical signatures.
    tia

  9. #9
    Join Date
    Apr 2004
    Posts
    102

    Re: get computer name

    Quote Originally Posted by memeloo View Post
    maybe this will help you http://www.tech-archive.net/Archive/...4-04/4001.html
    almost exacly what you need
    Took the above sample and cleaned it up a little....

    Code:
    using System;
    using System.Text;
    using System.Runtime.InteropServices;
    using System.ComponentModel;
    namespace Sample
    {
        class Program
        {
            [DllImport("winspool.drv", CharSet = CharSet.Unicode, ExactSpelling = false,
    		CallingConvention = CallingConvention.StdCall, SetLastError = true)]
            public static extern int OpenPrinter(string pPrinterName, out IntPtr phPrinter, IntPtr pDefault);
    
            [DllImport("winspool.Drv", EntryPoint = "GetPrinterA", SetLastError = true,
                CharSet = CharSet.Ansi, ExactSpelling = true,
                CallingConvention = CallingConvention.StdCall)]
            private static extern bool GetPrinter(IntPtr hPrinter, Int32 dwLevel,
            IntPtr pPrinter, Int32 dwBuf, out Int32 dwNeeded);
    
            [DllImport("winspool.drv", CharSet = CharSet.Auto)]
            public static extern int EnumJobs(IntPtr hPrinter, int FirstJob, int
            NoJobs, int Level, IntPtr pInfo, int cdBuf, out int pcbNeeded, out int
            pcReturned);
    
            [DllImport("winspool.drv", SetLastError = true)]
            static extern int ClosePrinter(IntPtr hPrinter);
    
            [StructLayout(LayoutKind.Sequential)]
            public struct SYSTEMTIME
            {
                public short wYear;
                public short wMonth;
                public short wDayOfWeek;
                public short wDay;
                public short wHour;
                public short wMinute;
                public short wSecond;
                public short wMilliseconds;
            }
            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
            public struct JOB_INFO_1
            {
                public int JobId;
                public string pPrinterName;
                public string pMachineName;
                public string pUserName;
                public string pDocument;
                public string pDatatype;
                public string pStatus;
                public int Status;
                public int Priority;
                public int Position;
                public int TotalPages;
                public int PagesPrinted;
                public SYSTEMTIME Submitted;
            }
    
            [StructLayout(LayoutKind.Sequential)]
            struct PRINTER_DEFAULTS
            {
                public IntPtr pDatatype;
                public IntPtr pDevMode;
                public int DesiredAccess;
            }
    
            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
            public struct PRINTER_INFO_2
            {
                [MarshalAs(UnmanagedType.LPTStr)]
                public string pServerName;
                [MarshalAs(UnmanagedType.LPTStr)]
                public string pPrinterName;
                [MarshalAs(UnmanagedType.LPTStr)]
                public string pShareName;
                [MarshalAs(UnmanagedType.LPTStr)]
                public string pPortName;
                [MarshalAs(UnmanagedType.LPTStr)]
                public string pDriverName;
                [MarshalAs(UnmanagedType.LPTStr)]
                public string pComment;
                [MarshalAs(UnmanagedType.LPTStr)]
                public string pLocation;
                public IntPtr pDevMode;
                [MarshalAs(UnmanagedType.LPTStr)]
                public string pSepFile;
                [MarshalAs(UnmanagedType.LPTStr)]
                public string pPrintProcessor;
                [MarshalAs(UnmanagedType.LPTStr)]
                public string pDatatype;
                [MarshalAs(UnmanagedType.LPTStr)]
                public string pParameters;
                public IntPtr pSecurityDescriptor;
                public uint Attributes;
                public uint Priority;
                public uint DefaultPriority;
                public uint StartTime;
                public uint UntilTime;
                public uint Status;
                public uint cJobs;
                public uint AveragePPM;
            }
    
            private const int PRINTER_ACCESS_ADMINISTER = 0x4;
            private const int PRINTER_ACCESS_USE = 0x8;
            private const int STANDARD_RIGHTS_REQUIRED = 0xF0000;
            private const int PRINTER_ALL_ACCESS =
                (STANDARD_RIGHTS_REQUIRED | PRINTER_ACCESS_ADMINISTER
                | PRINTER_ACCESS_USE);
    
            static void AccessPrinter(string printerName)
            {
                int result;
                IntPtr hPrinter;
                int nBytesNeeded;
                int pcbNeeded;
                int pcReturned;
                IntPtr ptrPrinterInfo;
                int nRet;
                int nJunk;
    
                PRINTER_DEFAULTS pd = new PRINTER_DEFAULTS();
                PRINTER_INFO_2 pinfo = new PRINTER_INFO_2();
                int rawsize = Marshal.SizeOf(pd);
                IntPtr pdPtr = Marshal.AllocHGlobal(rawsize);
                pd.DesiredAccess = PRINTER_ALL_ACCESS;
                Marshal.StructureToPtr(pd, pdPtr, true);
                result = OpenPrinter(printerName, out hPrinter, pdPtr);
    
                if (result == 0)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
                GetPrinter(hPrinter, 2, IntPtr.Zero, 0, out nBytesNeeded);
                if (nBytesNeeded <= 0)
                {
                    throw new System.Exception("Unable to allocate memory");
                }
                else
                {
                    ptrPrinterInfo = Marshal.AllocCoTaskMem(nBytesNeeded);
    
                    ptrPrinterInfo = Marshal.AllocHGlobal(nBytesNeeded);
                    nRet = Convert.ToInt32(GetPrinter(hPrinter, 2,
                        ptrPrinterInfo, nBytesNeeded, out nJunk));
                    if (nRet == 0)
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                pinfo = (PRINTER_INFO_2)Marshal.PtrToStructure(ptrPrinterInfo,
                    typeof(PRINTER_INFO_2));
                EnumJobs(hPrinter, 0, (int)pinfo.cJobs, 1, IntPtr.Zero, 0, out pcbNeeded, out pcReturned);
                IntPtr pData = Marshal.AllocHGlobal(pcbNeeded);
                EnumJobs(hPrinter, 0, (int)pinfo.cJobs, 1, pData, pcbNeeded, out pcbNeeded, out pcReturned);
                JOB_INFO_1[] jobs = new JOB_INFO_1[pcReturned];
                int pTemp = pData.ToInt32(); //start pointer 
                for (int i = 0; i < pcReturned; ++i)
                {
                    jobs[i] = (JOB_INFO_1)Marshal.PtrToStructure(new
                        IntPtr(pTemp), typeof(JOB_INFO_1));
                    Console.WriteLine(jobs[i].JobId.ToString() + Environment.NewLine);
                    Console.WriteLine(jobs[i].pUserName + Environment.NewLine);
                          pTemp+= Marshal.SizeOf( typeof(JOB_INFO_1) ); 
                }
                Marshal.FreeHGlobal(pData);
                ClosePrinter(hPrinter);
                for (int j = 0; j < pcReturned; ++j)
                {
                    Console.WriteLine(jobs[j].pMachineName);
                    Console.WriteLine(jobs[j].pUserName);
                }
            }
            static void Main()
            {
    		     AccessPrinter(@"\\myServer\myPrinter");
            }
        }
    }

  10. #10
    Join Date
    Oct 2007
    Posts
    84

    Re: get computer name

    exactly what i needed.
    thanks a lot!
    one more thing how can i insert the machinename in a listbox?
    i tried everything but it didnt work

    tia
    Last edited by homer.favenir; December 21st, 2009 at 04:59 AM.

  11. #11
    Join Date
    Apr 2004
    Posts
    102

    Re: get computer name

    one more thing how can i insert the machinename in a listbox?
    Does the following work for you?

    Code:
    string test= "Testing";
    myListBox.Items.Add( test );

  12. #12
    Join Date
    Oct 2008
    Location
    Cologne, Germany
    Posts
    756

    Re: get computer name

    Quote Originally Posted by homer.favenir View Post
    one more thing how can i insert the machinename in a listbox?
    banned by google? http://msdn.microsoft.com/en-us/libr...03(VS.71).aspx
    Quote Originally Posted by homer.favenir View Post
    i tried everything but it didnt work
    if you had tried everything it would certainly work.
    win7 x86, VS 2008 & 2010, C++/CLI, C#, .NET 3.5 & 4.0, VB.NET, VBA... WPF is comming

    remeber to give feedback you think my response deserves recognition? perhaps you may want to click the Rate this post link/button and add to my reputation

    private lessons are not an option so please don't ask for help in private, I won't replay

    if you use Opera and you'd like to have the tab-button functionality for the texteditor take a look at my Opera Tab-UserScirpt; and if you know how to stop firefox from jumping to the next control when you hit tab let me know

  13. #13
    Join Date
    Oct 2007
    Posts
    84

    Re: get computer name

    i know how to add items in a listbox
    but from the code above that gets the machine name, i cant find how to put it in a variable and insert it in listbox.

    i tried everything, do some trial and error, but i dont know how to do it correctly.

    thanks

  14. #14
    Join Date
    Apr 2004
    Posts
    102

    Re: get computer name

    Quote Originally Posted by homer.favenir View Post
    i know how to add items in a listbox
    but from the code above that gets the machine name, i cant find how to put it in a variable and insert it in listbox.

    i tried everything, do some trial and error, but i dont know how to do it correctly.

    thanks
    Code:
    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    using System.Runtime.InteropServices;
    
    public class ListBoxItemAdd : System.Windows.Forms.Form
    {
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.ListBox listBox1;
    
        [DllImport("winspool.drv", CharSet = CharSet.Unicode, ExactSpelling = false,
              CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        public static extern int OpenPrinter(string pPrinterName, out IntPtr phPrinter, IntPtr pDefault);
    
        [DllImport("winspool.Drv", EntryPoint = "GetPrinterA", SetLastError = true,
            CharSet = CharSet.Ansi, ExactSpelling = true,
            CallingConvention = CallingConvention.StdCall)]
        private static extern bool GetPrinter(IntPtr hPrinter, Int32 dwLevel,
        IntPtr pPrinter, Int32 dwBuf, out Int32 dwNeeded);
    
        [DllImport("winspool.drv", CharSet = CharSet.Auto)]
        public static extern int EnumJobs(IntPtr hPrinter, int FirstJob, int
        NoJobs, int Level, IntPtr pInfo, int cdBuf, out int pcbNeeded, out int
        pcReturned);
    
        [DllImport("winspool.drv", SetLastError = true)]
        static extern int ClosePrinter(IntPtr hPrinter);
    
        [StructLayout(LayoutKind.Sequential)]
        public struct SYSTEMTIME
        {
            public short wYear;
            public short wMonth;
            public short wDayOfWeek;
            public short wDay;
            public short wHour;
            public short wMinute;
            public short wSecond;
            public short wMilliseconds;
        }
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct JOB_INFO_1
        {
            public int JobId;
            public string pPrinterName;
            public string pMachineName;
            public string pUserName;
            public string pDocument;
            public string pDatatype;
            public string pStatus;
            public int Status;
            public int Priority;
            public int Position;
            public int TotalPages;
            public int PagesPrinted;
            public SYSTEMTIME Submitted;
        }
        [StructLayout(LayoutKind.Sequential)]
        struct PRINTER_DEFAULTS
        {
            public IntPtr pDatatype;
            public IntPtr pDevMode;
            public int DesiredAccess;
        }
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct PRINTER_INFO_2
        {
            [MarshalAs(UnmanagedType.LPTStr)]
            public string pServerName;
            [MarshalAs(UnmanagedType.LPTStr)]
            public string pPrinterName;
            [MarshalAs(UnmanagedType.LPTStr)]
            public string pShareName;
            [MarshalAs(UnmanagedType.LPTStr)]
            public string pPortName;
            [MarshalAs(UnmanagedType.LPTStr)]
            public string pDriverName;
            [MarshalAs(UnmanagedType.LPTStr)]
            public string pComment;
            [MarshalAs(UnmanagedType.LPTStr)]
            public string pLocation;
            public IntPtr pDevMode;
            [MarshalAs(UnmanagedType.LPTStr)]
            public string pSepFile;
            [MarshalAs(UnmanagedType.LPTStr)]
            public string pPrintProcessor;
            [MarshalAs(UnmanagedType.LPTStr)]
            public string pDatatype;
            [MarshalAs(UnmanagedType.LPTStr)]
            public string pParameters;
            public IntPtr pSecurityDescriptor;
            public uint Attributes;
            public uint Priority;
            public uint DefaultPriority;
            public uint StartTime;
            public uint UntilTime;
            public uint Status;
            public uint cJobs;
            public uint AveragePPM;
        }
    
        private const int PRINTER_ACCESS_ADMINISTER = 0x4;
        private const int PRINTER_ACCESS_USE = 0x8;
        private const int STANDARD_RIGHTS_REQUIRED = 0xF0000;
        private const int PRINTER_ALL_ACCESS =
            (STANDARD_RIGHTS_REQUIRED | PRINTER_ACCESS_ADMINISTER
            | PRINTER_ACCESS_USE);
    
        static void AccessPrinter(string printerName, ref JOB_INFO_1[] jobout, ref int count)
        {
            int result;
            IntPtr hPrinter;
            int nBytesNeeded;
            int pcbNeeded;
            int pcReturned;
            IntPtr ptrPrinterInfo;
            int nRet;
            int nJunk;
    
            PRINTER_DEFAULTS pd = new PRINTER_DEFAULTS();
            PRINTER_INFO_2 pinfo = new PRINTER_INFO_2();
            int rawsize = Marshal.SizeOf(pd);
            IntPtr pdPtr = Marshal.AllocHGlobal(rawsize);
            pd.DesiredAccess = PRINTER_ALL_ACCESS;
            Marshal.StructureToPtr(pd, pdPtr, true);
            result = OpenPrinter(printerName, out hPrinter, pdPtr);
    
            if (result == 0)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            GetPrinter(hPrinter, 2, IntPtr.Zero, 0, out nBytesNeeded);
            if (nBytesNeeded <= 0)
            {
                throw new System.Exception("Unable to allocate memory");
            }
            else
            {
                ptrPrinterInfo = Marshal.AllocCoTaskMem(nBytesNeeded);
    
                ptrPrinterInfo = Marshal.AllocHGlobal(nBytesNeeded);
                nRet = Convert.ToInt32(GetPrinter(hPrinter, 2,
                    ptrPrinterInfo, nBytesNeeded, out nJunk));
                if (nRet == 0)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            pinfo = (PRINTER_INFO_2)Marshal.PtrToStructure(ptrPrinterInfo,
                typeof(PRINTER_INFO_2));
            EnumJobs(hPrinter, 0, (int)pinfo.cJobs, 1, IntPtr.Zero, 0, out pcbNeeded, out pcReturned);
            IntPtr pData = Marshal.AllocHGlobal(pcbNeeded);
            EnumJobs(hPrinter, 0, (int)pinfo.cJobs, 1, pData, pcbNeeded, out pcbNeeded, out pcReturned);
            JOB_INFO_1[] jobs = new JOB_INFO_1[pcReturned];
            int pTemp = pData.ToInt32(); //start pointer 
            for (int i = 0; i < pcReturned; ++i)
            {
                jobs[i] = (JOB_INFO_1)Marshal.PtrToStructure(new
                    IntPtr(pTemp), typeof(JOB_INFO_1));
                Console.WriteLine(jobs[i].JobId.ToString() + Environment.NewLine);
                Console.WriteLine(jobs[i].pUserName + Environment.NewLine);
                pTemp += Marshal.SizeOf(typeof(JOB_INFO_1));
            }
            Marshal.FreeHGlobal(pData);
            ClosePrinter(hPrinter);
            jobout = jobs;
            count = pcReturned;
        }
    
        private System.ComponentModel.Container components = null;
    
        public ListBoxItemAdd()
        {
            InitializeComponent();
    
        }
    
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }
    
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.listBox1 = new System.Windows.Forms.ListBox();
            this.SuspendLayout();
    
            this.button1.Font = new System.Drawing.Font("Verdana", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
            this.button1.Location = new System.Drawing.Point(16, 16);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(80, 32);
            this.button1.TabIndex = 0;
            this.button1.Text = "Add";
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // listBox1
            // 
            this.listBox1.BackColor = System.Drawing.Color.Red;
            this.listBox1.ForeColor = System.Drawing.SystemColors.HighlightText;
            this.listBox1.Location = new System.Drawing.Point(8, 64);
            this.listBox1.Name = "listBox1";
            this.listBox1.Size = new System.Drawing.Size(272, 238);
            this.listBox1.TabIndex = 2;
            // 
            // ListBoxItemAdd
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(328, 318);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                        this.listBox1,
                                        this.button1});
            this.Name = "ListBoxItemAdd";
            this.Text = "ListBoxItemAdd";
            this.ResumeLayout(false);
    
        }
    
        [STAThread]
        static void Main()
        {
            Application.Run(new ListBoxItemAdd());
        }
    
        private void button1_Click(object sender, System.EventArgs e)
        {
            JOB_INFO_1[] j = new JOB_INFO_1[1000];
            int i = 0;
            AccessPrinter(@"\\myServer\myPrinter", ref j, ref i);
            for (int x = 0; x < i; ++x)
            {
                listBox1.Items.Add(j[x].pMachineName);
            }
        }
    }
    Last edited by BobS0327; December 22nd, 2009 at 02:49 PM. Reason: Change printer string

  15. #15
    Join Date
    Oct 2007
    Posts
    84

    Re: get computer name

    thanks for the reply... i really appreciate it...
    but it has an error...
    Code:
    Error	1	Program 'C:\Documents and Settings\homer.favenir.AAIGLOBAL\Local Settings\Application Data\Temporary Projects\WindowsFormsApplication1\obj\Debug\WindowsFormsApplication1.exe' has more than one entry point defined: 'ListBoxItemAdd.Main()'.  Compile with /main to specify the type that contains the entry point.	C:\Documents and Settings\homer.favenir.AAIGLOBAL\Local Settings\Application Data\Temporary Projects\WindowsFormsApplication1\Form1.cs	230	17	WindowsFormsApplication1
    Code:
    [B]Error	2	Program 'C:\Documents and Settings\homer.favenir.AAIGLOBAL\Local Settings\Application Data\Temporary Projects\WindowsFormsApplication1\obj\Debug\WindowsFormsApplication1.exe' has more than one entry point defined: 'WindowsFormsApplication1.Program.Main()'.  Compile with /main to specify the type that contains the entry point.	C:\Documents and Settings\homer.favenir.AAIGLOBAL\Local Settings\Application Data\Temporary Projects\WindowsFormsApplication1\Program.cs	14	21	WindowsFormsApplication1

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured