Exemplo n.º 1
0
        public bool IsModuleLoaded()
        {
            Guid classGuid = Guid.Empty;

            if (ClassType != null)
            {
                classGuid = ClassType.GUID;
            }
            else
            {
                classGuid = ClassId;
            }

            Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey("CLSID\\{" + classGuid.ToString() + "}\\InprocServer32");
            if (rk == null)
            {
                return(false);
            }
            string classdllname = rk.GetValue(null).ToString();
            IntPtr libH         = KERNEL32.GetModuleHandle(classdllname);

            if (libH == IntPtr.Zero)
            {
                return(false);
            }

            return(true);
        }
Exemplo n.º 2
0
            /// <summary>
            /// Changes the properties of a device by calling the <see cref="SetupDiSetClassInstallParams"/> and <see cref="SetupDiChangeState"/> functions
            /// </summary>
            /// <param name="installFunction">The function to call</param>
            /// <param name="stateChange">The new state</param>
            /// <param name="scope">Scope for the change</param>
            /// <param name="hardwareProfile">HardwareProfile to use</param>
            public void ChangeProperty(DIF installFunction, DICS stateChange, DICS_FLAGS scope, uint hardwareProfile)
            {
                var p = new SP_PROPCHANGE_PARAMS();

                p.ClassInstallHeader.cbSize          = (uint)Marshal.SizeOf(p.ClassInstallHeader);
                p.ClassInstallHeader.InstallFunction = installFunction;
                p.StateChange = stateChange;
                p.Scope       = scope;
                p.HwProfile   = hardwareProfile;
                var deviceInfo = this.deviceInfo;
                { //Set parameters
                    if (!SetupDiSetClassInstallParams(Handle, ref deviceInfo, ref p, (uint)Marshal.SizeOf(p)))
                    {
                        throw new Win32ErrorException();
                    }
                    KERNEL32.CheckLastError();
                }
                { //Run change
                    if (!SetupDiChangeState(Handle, ref deviceInfo))
                    {
                        throw new Win32ErrorException();
                    }
                    KERNEL32.CheckLastError();
                }
                //if (!SetupDiCallClassInstaller(installFunction, m_Handle, ref deviceInfo))
            }
Exemplo n.º 3
0
        /// <summary>
        /// Reads the window text of the specified control handle.
        /// </summary>
        /// <param name="handle"></param>
        /// <returns></returns>
        public static string GetWindowText(IntPtr handle)
        {
            var sb = new StringBuilder(64000);

            _ = USER32.GetWindowText(handle, sb, sb.Capacity);
            KERNEL32.CheckLastError();
            return(sb.ToString());
        }
Exemplo n.º 4
0
        private object GetClassInstance(Guid classguid, Guid interfguid, Guid classfactoryguid, Guid classfactory2guid)
        {
            object classinstance = null;

            // create instance via raw dll functions
            // ensures we get the real vtable
            try
            {
                if (classinstance == null)
                {
                    // Single do..while loop - to support "break;"
                    do
                    {
                        Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey("CLSID\\{" + classguid.ToString() + "}\\InprocServer32");
                        if (rk == null)
                        {
                            break;
                        }
                        string classdllname = rk.GetValue(null).ToString();
                        IntPtr libH         = KERNEL32.LoadLibrary(classdllname);
                        if (libH == IntPtr.Zero)
                        {
                            break;
                        }
                        IntPtr factoryFunc = KERNEL32.GetProcAddress(libH, "DllGetClassObject");
                        if (factoryFunc == IntPtr.Zero)
                        {
                            break;
                        }
                        DllGetClassObjectDelegate factoryDel = (DllGetClassObjectDelegate)Marshal.GetDelegateForFunctionPointer(factoryFunc, typeof(DllGetClassObjectDelegate));
                        object classfactoryO;
                        // Try with IClassFactory first
                        factoryDel(ref classguid, ref classfactoryguid, out classfactoryO);
                        if (classfactoryO != null)
                        {
                            IClassFactory classfactory = (IClassFactory)classfactoryO;
                            classfactory.CreateInstance(null, ref interfguid, out classinstance);
                            Marshal.FinalReleaseComObject(classfactory);
                        }
                        else
                        {
                            // Now try with IClassFactory2
                            factoryDel(ref classguid, ref classfactory2guid, out classfactoryO);
                            if (classfactoryO == null)
                            {
                                break;
                            }
                            IClassFactory2 classfactory = (IClassFactory2)classfactoryO;
                            classinstance = classfactory.CreateInstance(null, interfguid);
                            Marshal.FinalReleaseComObject(classfactory);
                        }
                    } while (false);
                }
            }
            catch { }

            return(classinstance);
        }
Exemplo n.º 5
0
 /************************************************************************************/
 protected IntPtr OpenFile()
 {
     /// Used CreateFile because I wanted to open a file handle ONLY ONCE.
     /// Not three times to get existance, size, blah blah.
     return(KERNEL32.CreateFile(
                m_strFilePath,
                KERNEL32.FileAccess.ReadData | KERNEL32.FileAccess.ReadAttributes | KERNEL32.FileAccess.WriteData,
                KERNEL32.FileShareMode.Read | KERNEL32.FileShareMode.Write | KERNEL32.FileShareMode.Delete,
                IntPtr.Zero,
                KERNEL32.FileCreationDisposition.OpenExisting,
                KERNEL32.FileFlagsAndAttributes.FlagRandomAccess,
                IntPtr.Zero));
 }
Exemplo n.º 6
0
        public static bool ShutdownLocalhost(ShutdownEnum.ExitWindows options, ShutdownEnum.ShutdownReason reason)
        {
            TokPriv1Luid tp;
            IntPtr       hproc   = KERNEL32.getCurrentProcess();
            IntPtr       zeroPtr = IntPtr.Zero;

            ADVAPI32.OpenProcessToken(hproc, ADVAPI32.TOKEN_ADJUST_PRIVILEGES | ADVAPI32.TOKEN_QUERY, ref zeroPtr);
            tp.Count = 1;
            tp.Luid  = 0;
            tp.Attr  = ADVAPI32.SE_PRIVILEGE_ENABLED;
            ADVAPI32.LookupPrivilegeValue(null, ADVAPI32.SE_SHUTDOWN_NAME, ref tp.Luid);
            ADVAPI32.AdjustTokenPrivileges(zeroPtr, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
            return(USER32.exitWindowsEx(options, reason));
        }
Exemplo n.º 7
0
        /************************************************************************************/
        /// <summary>
        /// This is proven to work even while the file is locked.
        /// </summary>
        public void ClearLogFile()
        {
            IntPtr hFile = OpenFile();

            if (hFile != KERNEL32.INVALID_HANDLE_VALUE)
            {
                long lNewPointer = 0;
                KERNEL32.SetFilePointerEx(hFile, 0, ref lNewPointer, KERNEL32.FilePointerMoveMethod.Beginning);
                KERNEL32.SetEndOfFile(hFile);
                KERNEL32.CloseHandle(hFile);

                ResetCounters();
            }
            return;
        }
Exemplo n.º 8
0
        public static void HookKeyboard(HookProc proc)
        {
            using (Process curProcess = Process.GetCurrentProcess())
                using (ProcessModule curModule = curProcess.MainModule)
                {
                    var module = KERNEL32.GetModuleHandle(curModule.ModuleName);

                    UnhookKeyboard();

                    HookProc hook = (int nCode, IntPtr wParam, IntPtr lParam) => {
                        proc(nCode, wParam, lParam);

                        return(USER32.CallNextHookEx(_hHook, nCode, wParam, lParam));
                    };

                    _hHook = USER32.SetWindowsHookEx(WH_KEYBOARD_LL, hook, module, 0);
                }
        }
Exemplo n.º 9
0
        public void Impersonate(string userName, string domainName, string password, LogonType logonType, LogonProvider logonProvider)
        {
            UndoImpersonation();

            IntPtr logonToken          = IntPtr.Zero;
            IntPtr logonTokenDuplicate = IntPtr.Zero;

            try
            {
                _wic = WindowsIdentity.Impersonate(IntPtr.Zero);

                if (ADVAPI32.LogonUser(userName, domainName, password, (int)logonType, (int)logonProvider, ref logonToken) != 0)
                {
                    if (ADVAPI32.DuplicateToken(logonToken, (int)ImpersonationLevel.SecurityIdentification, ref logonTokenDuplicate) != 0)
                    {
                        var wi = new WindowsIdentity(logonTokenDuplicate);
                        wi.Impersonate();
                    }
                    else
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                else
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            finally
            {
                if (logonToken != IntPtr.Zero)
                {
                    KERNEL32.CloseHandle(logonToken);
                }

                if (logonTokenDuplicate != IntPtr.Zero)
                {
                    KERNEL32.CloseHandle(logonTokenDuplicate);
                }
            }
        }
Exemplo n.º 10
0
        /************************************************************************************/
        /// <summary>
        /// Unlike ACT, this should work at any time while EQ2 has the file locked.
        /// It isn't perfect and might have some overlap but it's good enough.
        /// NOTE: The log file can't be renamed while in use.
        /// </summary>
        public void SplitLogFile()
        {
            try
            {
                string strNewFileName = string.Format("{0} {1:yyyy-MM-dd HHmmssfffffff}", Path.GetFileNameWithoutExtension(m_strFilePath), DateTime.UtcNow);
                strNewFileName += Path.GetExtension(m_strFilePath);
                string strNewFilePath = Path.Combine(Path.GetDirectoryName(m_strFilePath), strNewFileName);

                if (!KERNEL32.CopyFile(m_strFilePath, strNewFilePath, false))
                {
                    return;
                }

                /// This is the tricky moment. Right here it's possible that more lines are added to the log file.

                ClearLogFile();
            }
            catch             //(Exception ex)
            {
                /// Not sure yet what to do here, if anything.
            }
            return;
        }
Exemplo n.º 11
0
        /// <summary>
        /// Installs both or one of mouse and/or keyboard hooks and starts rasing events
        /// </summary>
        /// <exception cref="Win32ErrorException">Any windows problem.</exception>
        public void Start()
        {
            // install Mouse hook only if it is not installed and must be installed
            if (hMouseHook == IntPtr.Zero)
            {
                // Create an instance of HookProc.
                mouseHookProcedure = new USER32.HookProc(MouseHookProc);
                //install hook
                hMouseHook = USER32.SetWindowsHookEx(WH.MOUSE_LL, mouseHookProcedure, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
                //If SetWindowsHookEx fails.
                KERNEL32.CheckLastError();
                if (hMouseHook == IntPtr.Zero)
                {
                    //do cleanup
                    Stop(false);
                    throw new Win32ErrorException();
                }
            }

            // install Keyboard hook only if it is not installed and must be installed
            if (hKeyboardHook == IntPtr.Zero)
            {
                // Create an instance of HookProc.
                keyboardHookProcedure = new USER32.HookProc(KeyboardHookProc);
                //install hook
                hKeyboardHook = USER32.SetWindowsHookEx(WH.KEYBOARD_LL, keyboardHookProcedure, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
                //If SetWindowsHookEx fails.
                KERNEL32.CheckLastError();
                if (hKeyboardHook == IntPtr.Zero)
                {
                    //do cleanup
                    Stop(false);
                    throw new Win32ErrorException();
                }
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Enables the hook
        /// </summary>
        /// <returns>True if hook is enabled</returns>
        public bool EnableHook()
        {
            if (this.mseHook != IntPtr.Zero)
            {
                return(true);
            }

            this.mseHook = USER32.SetWindowsHookEx(HookType.WH_MOUSE_LL, this.mseCallbackDelegate, KERNEL32.GetModuleHandle(System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName), 0);
            return(this.mseHook != IntPtr.Zero);
        }
        /************************************************************************************/
        protected virtual bool OnCustomSlashCommand(string strCommand, string[] astrParameters)
        {
            string strCondensedParameters = string.Join(" ", astrParameters).Trim();

            switch (strCommand)
            {
            case "gc_assist":
            {
                Actor OffensiveTargetActor = GetNestedCombatAssistTarget(astrParameters[0]);
                if (OffensiveTargetActor != null)
                {
                    OffensiveTargetActor.DoTarget();
                }
                return(true);
            }

            /// Directly acquire an offensive target.
            case "gc_attack":
            {
                Actor MyTargetActor = MeActor.Target();
                if (MyTargetActor.IsValid)
                {
                    /// Don't bother filtering. Just grab the ID, let the other code determine if it's a legit target.
                    m_iOffensiveTargetID = MyTargetActor.ID;
                    Program.Log("Offensive target set to \"{0}\" ({1}).", MyTargetActor.Name, m_iOffensiveTargetID);
                }
                else
                {
                    Program.Log("Invalid target selected.");
                }
                return(true);
            }

            /// This is the assist call; direct the bot to begin combat.
            /// Essentially combines gc_assist and gc_attack.
            case "gc_attackassist":
            {
                if (astrParameters.Length != 1)
                {
                    Program.Log("gc_attackassist: Missing name of player to assist!");
                    return(true);
                }

                /// Force a recalculation.
                m_OffensiveTargetEncounterActorDictionary.Clear();

                Actor OffensiveTargetActor = GetNestedCombatAssistTarget(astrParameters[0]);
                if (OffensiveTargetActor == null)
                {
                    /// Combat is now cancelled.
                    /// Maybe the commanding player misclicked or clicked off intentionally, but it doesn't matter.
                    WithdrawFromCombat();
                }
                else
                {
                    /// Successful target acquisition.
                    m_iOffensiveTargetID = OffensiveTargetActor.ID;
                    Program.Log("New offensive target: {0}", OffensiveTargetActor.Name);

                    /// An assist command promotes AFK into neutral positioning.
                    if (m_ePositioningStance == PositioningStance.DoNothing)
                    {
                        ChangePositioningStance(PositioningStance.NeutralPosition);
                    }
                }

                return(true);
            }

            /// Begin dropping all group buffs.
            case "gc_cancelgroupbuffs":
            {
                Program.Log("Cancelling all maintained group effects...");
                m_bClearGroupMaintained = true;
                return(true);
            }

            /// Arbitrarily change an INI setting on the fly.
            case "gc_changesetting":
            {
                string strKey   = string.Empty;
                string strValue = string.Empty;

                int iEqualsPosition = strCondensedParameters.IndexOf(" ");
                if (iEqualsPosition == -1)
                {
                    strKey = strCondensedParameters;
                }
                else
                {
                    strKey   = strCondensedParameters.Substring(0, iEqualsPosition).TrimEnd();
                    strValue = strCondensedParameters.Substring(iEqualsPosition + 1).TrimStart();
                }

                if (!string.IsNullOrEmpty(strKey))
                {
                    Program.Log("Changing setting \"{0}\" to new value \"{1}\"...", strKey, strValue);

                    IniFile FakeIniFile = new IniFile();
                    FakeIniFile.WriteString(strKey, strValue);
                    FakeIniFile.Mode = IniFile.TransferMode.Read;
                    TransferINISettings(FakeIniFile);
                    ApplySettings();
                }
                return(true);
            }

            case "gc_debug":
            {
                if (astrParameters.Length == 0)
                {
                    Program.Log("gc_debug: No option specified!");
                    return(true);
                }

                switch (astrParameters[0])
                {
                case "whopet":
                    Program.Log("gc_debug whopet: Listing player's primary pet...");
                    FlexStringBuilder ThisBuilder = new FlexStringBuilder();
                    AppendActorInfo(ThisBuilder, 1, Me.Pet());
                    Program.Log("{0}", ThisBuilder.ToString());
                    return(true);

                case "fullaffinities":
                    Program.Log("Attempting to remove all affinity constraints on the process and its threads...");
                    uint   uiCurrentProcessID = KERNEL32.GetCurrentProcessId();
                    IntPtr hProcess           = KERNEL32.OpenProcess(KERNEL32.ProcessAccess.SetInformation | KERNEL32.ProcessAccess.QueryInformation, false, uiCurrentProcessID);
                    if (hProcess == KERNEL32.INVALID_HANDLE_VALUE)
                    {
                        Program.Log("Unable to open process {0}.", uiCurrentProcessID);
                        return(true);
                    }

                    UIntPtr uiProcessAffinityMask;
                    UIntPtr uiSystemProcessorMask;
                    KERNEL32.GetProcessAffinityMask(hProcess, out uiProcessAffinityMask, out uiSystemProcessorMask);
                    Program.Log("Process {0} previous affinity mask: 0x{1:X8}", uiCurrentProcessID, uiProcessAffinityMask);

                    KERNEL32.SetProcessAffinityMask(hProcess, uiSystemProcessorMask);
                    KERNEL32.CloseHandle(hProcess);

                    Program.Log("Attempting to remove all affinity constraints on the process threads...");
                    foreach (KERNEL32.THREADENTRY32 ThisThread in KERNEL32.EnumProcessThreads(uiCurrentProcessID))
                    {
                        IntPtr hThread = KERNEL32.OpenThread(KERNEL32.ThreadAccess.SetInformation | KERNEL32.ThreadAccess.QueryInformation, false, ThisThread.th32ThreadID);
                        if (hThread != IntPtr.Zero)
                        {
                            UIntPtr uiOldThreadAffinityMask = KERNEL32.SetThreadAffinityMask(hThread, uiSystemProcessorMask);
                            Program.Log("Thread {0} previous affinity mask: 0x{1:X8}", ThisThread.th32ThreadID, uiOldThreadAffinityMask);
                            KERNEL32.CloseHandle(hThread);
                        }
                        else
                        {
                            Program.Log("Can't open thread {0}.", ThisThread.th32ThreadID);
                        }
                    }
                    return(true);

                case "memstat":
                    Process CurrentProcess = Process.GetCurrentProcess();
                    Program.Log("Virtual Allocation: {0}", CustomFormatter.FormatByteCount(CurrentProcess.VirtualMemorySize64, "0.00"));
                    Program.Log("Working Set: {0}", CustomFormatter.FormatByteCount(CurrentProcess.WorkingSet64, "0.00"));
                    Program.Log(".NET Heap Allocation: {0}", CustomFormatter.FormatByteCount(GC.GetTotalMemory(false), "0.00"));
                    Program.Log("Threads: {0}", CurrentProcess.Threads.Count);
                    return(true);
                }

                Program.Log("Usage: gc_debug (whopet|fullaffinities|memstat)");
                return(true);
            }

            case "gc_defaultverb":
            {
                string strActorName        = strCondensedParameters;
                Actor  IntendedTargetActor = null;

                /// Grab the targetted actor.
                if (string.IsNullOrEmpty(strActorName))
                {
                    Actor CurrentTargetActor = MeActor.Target();
                    if (CurrentTargetActor.IsValid)
                    {
                        IntendedTargetActor = CurrentTargetActor;
                    }
                }

                /// Grab the so-named actor nearest to the commander.
                else
                {
                    double fNearestDistance = 50.0;
                    foreach (Actor ThisActor in EnumActors(strActorName))
                    {
                        if (ThisActor.Name != strActorName)
                        {
                            continue;
                        }

                        double fThisDistance = ThisActor.Distance;
                        if (fThisDistance < fNearestDistance)
                        {
                            fNearestDistance    = fThisDistance;
                            IntendedTargetActor = ThisActor;
                        }
                    }
                }

                /// No such actor found.
                if (IntendedTargetActor == null)
                {
                    Program.Log("gc_defaultverb: actor not found.");
                }
                else
                {
                    Program.Log("gc_defaultverb: Attempting to apply default verb on actor \"{0}\" ({1}).", strActorName, IntendedTargetActor.ID);
                    IntendedTargetActor.DoubleClick();
                }

                return(true);
            }

            case "gc_distance":
            {
                Actor MyTargetActor = MeActor.Target();
                if (MyTargetActor.IsValid)
                {
                    string strOutput = string.Format("Distance to target \"{0}\" ({1}): {2} meter(s).", MyTargetActor.Name, MyTargetActor.ID, MyTargetActor.Distance);
                    RunCommand("/announce {0}", strOutput);
                    Program.Log(strOutput);
                }
                return(true);
            }

            case "gc_dumpabilities":
            {
                /// Dump all abilities to a .CSV file specified as a parameter, on the next knowledge book refresh.
                s_strKnowledgeBookDumpPath = strCondensedParameters;
                s_bRefreshKnowledgeBook    = true;
                return(true);
            }

            case "gc_exit":
            {
                Program.Log("Exit command received!");
                s_bContinueBot = false;
                return(true);
            }

            case "gc_exitprocess":
            {
                Process.GetCurrentProcess().Kill();
                return(true);
            }

            case "gc_findactor":
            {
                string strSearchString = strCondensedParameters.ToLower();

                TrackNearestActors(5, true, strSearchString);
                return(true);
            }

            case "gc_openini":
            {
                Program.SafeShellExecute(s_strCurrentINIFilePath);
                return(true);
            }

            case "gc_openoverridesini":
            {
                Program.SafeShellExecute(s_strSharedOverridesINIFilePath);
                return(true);
            }

            case "gc_reloadsettings":
            {
                ReadINISettings();
                ReleaseAllKeys();                         /// If there's a bug, this will cure it. If not, no loss.
                s_bRefreshKnowledgeBook = true;
                return(true);
            }

            case "gc_stance":
            {
                if (astrParameters.Length < 1)
                {
                    Program.Log("gc_stance failed: Missing stance parameter.");
                    return(true);
                }

                string strStance = astrParameters[0].ToLower();
                switch (strStance)
                {
                case "afk":
                    Program.Log("Now ignoring all non-stance commands.");
                    ChangePositioningStance(PositioningStance.DoNothing);
                    break;

                case "customfollow":
                    m_fCurrentMovementTargetCoordinateTolerance = m_fCustomAutoFollowMaximumRange;
                    m_strPositionalCommandingPlayer             = GetFirstExistingPartyMember(m_astrAutoFollowTargets, false);
                    ChangePositioningStance(PositioningStance.CustomAutoFollow);
                    break;

                case "shadow":
                    m_fCurrentMovementTargetCoordinateTolerance = m_fStayInPlaceTolerance;
                    m_strPositionalCommandingPlayer             = GetFirstExistingPartyMember(m_astrAutoFollowTargets, false);
                    ChangePositioningStance(PositioningStance.CustomAutoFollow);
                    break;

                case "normal":
                case "follow":
                    Program.Log("Positioning is now regular auto-follow.");
                    ChangePositioningStance(PositioningStance.AutoFollow);
                    break;

                case "neutral":
                    Program.Log("Positioning is now neutral.");
                    ChangePositioningStance(PositioningStance.NeutralPosition);
                    break;

                case "dash":
                    Program.Log("Dashing forward.");
                    ChangePositioningStance(PositioningStance.ForwardDash);
                    break;

                case "stay":
                    Program.Log("Locking position to where the commanding player is now standing.");
                    m_strPositionalCommandingPlayer = GetFirstExistingPartyMember(m_astrAutoFollowTargets, false);
                    ChangePositioningStance(PositioningStance.StayInPlace);
                    break;

                case "stayat":
                    if (astrParameters.Length >= 4)
                    {
                        Point3D NewSpot = new Point3D();
                        if (double.TryParse(astrParameters[1], out NewSpot.X) &&
                            double.TryParse(astrParameters[2], out NewSpot.Y) &&
                            double.TryParse(astrParameters[3], out NewSpot.Z))
                        {
                            m_strPositionalCommandingPlayer = string.Empty;
                            m_ptStayLocation = NewSpot;
                            ChangePositioningStance(PositioningStance.StayInPlace);
                        }
                        else
                        {
                            Program.Log("Bad coordinate input format.");
                        }
                    }
                    else
                    {
                        Program.Log("You need 3 values to form a 3-D coordinate, but you specified {0}.", astrParameters.Length - 1);
                    }
                    break;

                case "stayself":
                    Program.Log("Locking position to where you are now standing.");
                    m_strPositionalCommandingPlayer = Name;
                    ChangePositioningStance(PositioningStance.StayInPlace);
                    break;

                default:
                    Program.Log("Stance not recognized.");
                    break;
                }

                return(true);
            }

            case "gc_spawnwatch":
            {
                m_bSpawnWatchTargetAnnounced = false;
                m_strSpawnWatchTarget        = strCondensedParameters.ToLower().Trim();
                Program.Log("Bot will now scan for actor \"{0}\".", m_strSpawnWatchTarget);
                ChangePositioningStance(PositioningStance.SpawnWatch);
                return(true);
            }

            /// A super-powerful direct targetter.
            case "gc_target":
            {
                Actor  TargetActor     = null;
                string strSearchString = strCondensedParameters.ToLower();

                /// If they give an actual actor ID, then that's awesome.
                int iActorID = -1;
                if (int.TryParse(strSearchString, out iActorID))
                {
                    TargetActor = GetActor(iActorID);
                }
                else
                {
                    foreach (Actor ThisActor in EnumActors())
                    {
                        if (ThisActor.Name.ToLower().Contains(strSearchString))
                        {
                            TargetActor = ThisActor;
                            break;
                        }
                    }
                }

                if (TargetActor != null)
                {
                    TargetActor.DoTarget();
                }
                return(true);
            }

            /// Update the waypoint at a regular interval with the nearest location of an actor search string.
            case "gc_trackactor":
            {
                if (astrParameters.Length < 1)
                {
                    Program.Log("gc_trackactor failed: Missing parameter.");
                    return(true);
                }

                string strInterval = astrParameters[0].Trim().ToLower();
                if (strInterval == "off")
                {
                    RunCommand("/waypoint_cancel");
                    Program.Log("Actor tracking mode disabled.");
                    m_bTrackActor = false;
                    return(true);
                }

                double fIntervalSeconds = 0;
                if (!double.TryParse(strInterval, out fIntervalSeconds) || fIntervalSeconds < 0.0)
                {
                    Program.Log("gc_trackactor failed: Invalid interval parameter.");
                    return(false);
                }

                List <string> astrRemainingParameters = new List <string>(astrParameters);
                if (astrRemainingParameters.Count > 0)
                {
                    astrRemainingParameters.RemoveAt(0);
                }

                string strRemainingCondensedParameters = string.Join(" ", astrRemainingParameters.ToArray()).Trim().ToLower();

                /// Now we turn the mode on.
                m_TrackActorInterval        = TimeSpan.FromSeconds(fIntervalSeconds);
                m_NextTrackActorAttemptTime = CurrentCycleTimestamp;
                m_strTrackActorSubstring    = strRemainingCondensedParameters;
                m_bTrackActor = true;
                return(true);
            }

            /// Test the text-to-speech synthesizer using the current settings.
            case "gc_tts":
            {
                SayText(strCondensedParameters);
                return(true);
            }

            case "gc_version":
            {
                Program.DisplayVersion();
                Program.Log("ISXEQ2 Version: " + s_ISXEQ2.Version);
                return(true);
            }

            /// Clear the offensive target.
            case "gc_withdraw":
            {
                Program.Log("Offensive target withdrawn.");
                WithdrawFromCombat();
                return(true);
            }
            }

            return(false);
        }
Exemplo n.º 14
0
        /************************************************************************************/
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public bool ReadChanges()
        {
            bool   bSplitFile = false;
            IntPtr hFile      = KERNEL32.INVALID_HANDLE_VALUE;

            try
            {
                /// It may seem inefficient to close and reopen the handle every poll but that's the only way to get an accurate file size.
                if ((hFile = OpenFile()) == KERNEL32.INVALID_HANDLE_VALUE)
                {
                    Win32ErrorCode eError = KERNEL32.GetLastError();
                    return(false);
                }

                long lNewLength = 0;
                if (!KERNEL32.GetFileSizeEx(hFile, ref lNewLength))
                {
                    return(false);
                }

                /// File was presumably deleted or replaced.
                if (m_lLastFileEnd > lNewLength)
                {
                    m_lLastFileEnd = lNewLength;
                    return(false);
                }

                /// The file didn't change.
                if (m_lLastFileEnd == lNewLength)
                {
                    /// ...but now is a good time to split the file if needed.
                    if (m_lMaxFileSize != null && m_lLastFileEnd > m_lMaxFileSize.Value)
                    {
                        bSplitFile = true;
                    }

                    return(false);
                }

                /// We don't load the existing file when we first connect.
                if (m_bFirstCheck)
                {
                    m_bFirstCheck = false;
                }
                else
                {
                    string strContents = null;
                    using (FileStream ThisFile = new FileStream(new SafeFileHandle(hFile, false), FileAccess.Read))
                    {
                        ThisFile.Seek(m_lLastFileEnd, SeekOrigin.Begin);

                        /// We're safe; the log isn't UTF-16 so there's no risk of starting the read mid-character.
                        using (StreamReader ThisReader = new StreamReader(ThisFile, Encoding.ASCII))
                            strContents = ThisReader.ReadToEnd();
                    }
                    UnpackNewText(strContents);
                }

                m_lLastFileEnd = lNewLength;
            }
            catch             //(Exception e)
            {
                return(false);
            }
            finally
            {
                if (hFile == KERNEL32.INVALID_HANDLE_VALUE)
                {
                    KERNEL32.CloseHandle(hFile);
                    hFile = KERNEL32.INVALID_HANDLE_VALUE;
                }

                if (bSplitFile)
                {
                    SplitLogFile();
                }
            }

            return(true);
        }