⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cnetworkdrive.cs

📁 Hide-Delete icon from ToolBar32 for specific process , from command line arguments. TBBUTTON CSha
💻 CS
字号:
/*==============================================================================================================
  
  [ cNetworkDrive - Network Drive API Class ]
  -------------------------------------------
  Copyright (c)2006 aejw.com
  http://www.aejw.com/
  
Build:         0017 - May 2006
Thanks To:     'jsantos98' from CodeProject.com for his update allowing the local / drive not to specifyed

EULA:          Creative Commons - Attribution-ShareAlike 2.5
               http://creativecommons.org/licenses/by-sa/2.5/

Disclaimer:    THIS FILES / SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" 
               AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 
               TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 
               PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
               OWNER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
               EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
               TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
               OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
               THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR 
               TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 
               OF THE USE OF THIS FILES / SOFTWARE, EVEN IF ADVISED OF THE 
               POSSIBILITY OF SUCH DAMAGE. USE AT YOUR OWN RISK.
			   
==============================================================================================================*/
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace LicenseManage.BaseClasses
{
    /// <summary>
    /// Network Drive Interface
    /// </summary>
    public class NetworkDrive
    {

        #region API
        [DllImport("mpr.dll")]
        private static extern int WNetAddConnection2A(ref structNetResource pstNetRes, string psPassword, string psUsername, int piFlags);
        [DllImport("mpr.dll")]
        private static extern int WNetCancelConnection2A(string psName, int piFlags, int pfForce);
        [DllImport("mpr.dll")]
        private static extern int WNetConnectionDialog(int phWnd, int piType);
        [DllImport("mpr.dll")]
        private static extern int WNetDisconnectDialog(int phWnd, int piType);
        [DllImport("mpr.dll")]
        private static extern int WNetRestoreConnectionW(int phWnd, string psLocalDrive);

        [DllImport("mpr.dll")]
        private static extern int WNetGetConnection(string strLocalName, StringBuilder strbldRemoteName,
                                                    ref int intRemoteNameLength);

        [StructLayout(LayoutKind.Sequential)]
        private struct structNetResource
        {
            public int iScope;
            public int iType;
            public int iDisplayType;
            public int iUsage;
            public string sLocalName;
            public string sRemoteName;
            public string sComment;
            public string sProvider;
        }

        private const int RESOURCETYPE_DISK = 0x1;

        //Standard	
        private const int CONNECT_INTERACTIVE = 0x00000008;
        private const int CONNECT_PROMPT = 0x00000010;
        private const int CONNECT_UPDATE_PROFILE = 0x00000001;
        //IE4+
        private const int CONNECT_REDIRECT = 0x00000080;
        //NT5 only
        private const int CONNECT_COMMANDLINE = 0x00000800;
        private const int CONNECT_CMD_SAVECRED = 0x00001000;

        #endregion

        #region Propertys and options
        private bool lf_SaveCredentials = false;
        /// <summary>
        /// Option to save credentials are reconnection...
        /// </summary>
        public bool SaveCredentials
        {
            get { return (lf_SaveCredentials); }
            set { lf_SaveCredentials = value; }
        }
        private bool lf_Persistent = false;
        /// <summary>
        /// Option to reconnect drive after log off / reboot ...
        /// </summary>
        public bool Persistent
        {
            get { return (lf_Persistent); }
            set { lf_Persistent = value; }
        }
        private bool lf_Force = false;
        /// <summary>
        /// Option to force connection if drive is already mapped...
        /// or force disconnection if network path is not responding...
        /// </summary>
        public bool Force
        {
            get { return (lf_Force); }
            set { lf_Force = value; }
        }
        private bool ls_PromptForCredentials = false;
        /// <summary>
        /// Option to prompt for user credintals when mapping a drive
        /// </summary>
        public bool PromptForCredentials
        {
            get { return (ls_PromptForCredentials); }
            set { ls_PromptForCredentials = value; }
        }

        private string ls_Drive = "s:";
        /// <summary>
        /// Drive to be used in mapping / unmapping...
        /// </summary>
        public string LocalDrive
        {
            get { return (ls_Drive); }
            set
            {
                if (value.Length >= 1)
                {
                    ls_Drive = value.Substring(0, 1) + ":";
                }
                else
                {
                    ls_Drive = "";
                }
            }
        }
        private string ls_ShareName = "\\\\Computer\\C$";
        /// <summary>
        /// Share address to map drive to.
        /// </summary>
        public string ShareName
        {
            get { return (ls_ShareName); }
            set { ls_ShareName = value; }
        }
        #endregion

        #region Function mapping
        /// <summary>
        /// Map network drive
        /// </summary>
        public void MapDrive() { zMapDrive(null, null); }
        /// <summary>
        /// Map network drive (using supplied Password)
        /// </summary>
        public void MapDrive(string Password) { zMapDrive(null, Password); }
        /// <summary>
        /// Map network drive (using supplied Username and Password)
        /// </summary>
        public void MapDrive(string Username, string Password) { zMapDrive(Username, Password); }
        /// <summary>
        /// Unmap network drive
        /// </summary>
        public void DiscAllDrives() { UnMapAllDrives(); }
        /// <summary>
        /// Unmap all drives
        /// </summary>
        public void UnMapDrive() { zUnMapDrive(lf_Force); }
        /// <summary>
        /// Check / restore persistent network drive
        /// </summary>
        public void RestoreDrives() { zRestoreDrive(); }
        /// <summary>
        /// Display windows dialog for mapping a network drive
        /// </summary>
        public void ShowConnectDialog(Form ParentForm) { zDisplayDialog(ParentForm, 1); }
        /// <summary>
        /// Display windows dialog for disconnecting a network drive
        /// </summary>
        public void ShowDisconnectDialog(Form ParentForm) { zDisplayDialog(ParentForm, 2); }


        #endregion

        #region Core functions

        // Map network drive
        private void zMapDrive(string psUsername, string psPassword)
        {
            //create struct data
            structNetResource stNetRes = new structNetResource();
            stNetRes.iScope = 2;
            stNetRes.iType = RESOURCETYPE_DISK;
            stNetRes.iDisplayType = 3;
            stNetRes.iUsage = 1;
            stNetRes.sRemoteName = ls_ShareName;
            stNetRes.sLocalName = ls_Drive;
            //prepare params
            int iFlags = 0;
            if (lf_SaveCredentials) { iFlags += CONNECT_CMD_SAVECRED; }
            if (lf_Persistent) { iFlags += CONNECT_UPDATE_PROFILE; }
            if (ls_PromptForCredentials) { iFlags += CONNECT_INTERACTIVE + CONNECT_PROMPT; }
            if (psUsername.Length == 0) { psUsername = null; }
            if (psPassword.Length == 0)
            {
                psPassword = null;
            }
            //if force, unmap ready for new connection
            if (lf_Force) { try { zUnMapDrive(true); } catch { } }
            //call and return
            int i = WNetAddConnection2A(ref stNetRes, psPassword, psUsername, iFlags);
            if (i > 0) { throw new Win32Exception(i); }
        }


        // Unmap network drive	
        private void zUnMapDrive(bool pfForce)
        {
            //call unmap and return
            int iFlags = 0;
            if (lf_Persistent) { iFlags += CONNECT_UPDATE_PROFILE; }
            int i = WNetCancelConnection2A(ls_Drive, iFlags, Convert.ToInt32(pfForce));
            if (i != 0) i = WNetCancelConnection2A(ls_ShareName, iFlags, Convert.ToInt32(pfForce));  //disconnect if localname was null
            if (i > 0) { throw new Win32Exception(i); }
        }

        // Unmap network drive	
        private void UnMapDrive(string drive)
        {
            //call unmap and return
            int iFlags = 0;
            if (lf_Persistent) { iFlags += CONNECT_UPDATE_PROFILE; }
            int i = WNetCancelConnection2A(drive, iFlags, Convert.ToInt32(true));
            if (i != 0) i = WNetCancelConnection2A(ls_ShareName, iFlags, Convert.ToInt32(true));  //disconnect if localname was null
            if (i > 0) { throw new Win32Exception(i); }
        }



        private static void UnMapAllDrives()
        {





            ProcessStartInfo info = new ProcessStartInfo("cmd", @"/c net use * /d /y");//Export Registry entries
            info.RedirectStandardOutput = true;
            info.UseShellExecute = false;
            info.CreateNoWindow = true;

            Process p = new Process();
            p.StartInfo = info;
            p.Start();
            p.WaitForExit();

            /*
            string value = "wxzy";
            char[] chars = value.ToCharArray();
            string drv;
            //string SourceDirectory;
            //string anokato = @":\";
            Int32 miliseconds_to_sleep2 = 500;

            
            
            foreach (char ch in chars)
            {
                 //SourceDirectory = ch.ToString() + anokato.ToString();
                 
                 //DirectoryInfo source = new DirectoryInfo(SourceDirectory);

                 //if (!source.Exists) //Determine whether the source directory exists.
                 //    return;
                 //else
                 //{

                     CommandLineProcess cmd = new CommandLineProcess();
                     cmd.Command = "net";
                     cmd.UseComSpec = true;
                     if (ch >= 'a' && ch <= 'z')
                     {
                         drv = ch.ToString() + ":";
                         cmd.Arguments = "use " + drv + " /delete";
                         bool bSuccess = cmd.Start();
                         Thread.Sleep(miliseconds_to_sleep2);//let it rest

                     }
                 //}
             }*/
        }



            
        /* CommandLineProcess cmd = new CommandLineProcess();
            cmd.Command = "net";
            cmd.UseComSpec = true;
            foreach (char ch in chars)
            {
                if (ch >= 'a' && ch <= 'z')
                {
                drv = ch.ToString() + ":";
                cmd.Arguments = "use " + drv +" /delete";
                bool bSuccess = cmd.Start();
                }
            }

            
            foreach (char ch in chars)
            {
                if (ch >= 'a' && ch <= 'z')
                {
                        

                    //net use * /d /y
                    drv = ch.ToString() + ":";
                    System.Diagnostics.Process.Start("net.exe", "use " + drv + " /delete");
                    System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
                    //psi.FileName = "C:\\application.exe";
                    //psi.WorkingDirectory = "K:\\working\\directory";
                    //psi.WindowStyle = System.Diagnostics.
                    //ProcessWindowStyle.Maximized;
                    System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi);
                }
            }*/



        
        
        

        // Check / Restore a network drive
        private void zRestoreDrive()
        {
            //call restore and return
            int i = WNetRestoreConnectionW(0, null);
            if (i > 0) { throw new Win32Exception(i); }
        }

        // Display windows dialog
        private void zDisplayDialog(Form poParentForm, int piDialog)
        {
            int i = -1;
            int iHandle = 0;
            //get parent handle
            if (poParentForm != null)
            {
                iHandle = poParentForm.Handle.ToInt32();
            }
            //show dialog
            if (piDialog == 1)
            {
                i = WNetConnectionDialog(iHandle, RESOURCETYPE_DISK);
            }
            else if (piDialog == 2)
            {
                i = WNetDisconnectDialog(iHandle, RESOURCETYPE_DISK);
            }
            if (i > 0) { throw new Win32Exception(i); }
            //set focus on parent form
            if (poParentForm != null) poParentForm.BringToFront();
        }


        #endregion

    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -