/// <summary>
 /// Private Constructor, only called by the getter for the InstalledDevices property.
 /// </summary>
 /// <param name="deviceId">Position of this device in the list of all devices.</param>
 /// <param name="caps">Win32 Struct with device metadata</param>
 private OutputDevice(UIntPtr deviceId, Win32API.MIDIOUTCAPS caps)
     : base(caps.szPname)
 {
     this.deviceId = deviceId;
     this.caps = caps;
     this.isOpen = false;
 }
Beispiel #2
0
        /// <summary>
        /// Resolves A Specified LUID Value Into The Apropriate Windows Privilege
        /// </summary>
        public static String GetPrivilegeName(Win32API.LUID luid)
        {
            try
            {
                StringBuilder _PrivilegeName = new StringBuilder();

                //hold the length of the LuID Struct
                Int32 _NameLength = 0;

                //first method call is to get the _NameLength so we can allocate a buffer
                Win32API.LookupPrivilegeName(String.Empty, ref luid, _PrivilegeName, ref _NameLength);

                //make sure there is sufficient space in memory
                _PrivilegeName.EnsureCapacity(_NameLength);

                //look up the privilage name
                if (Win32API.LookupPrivilegeName(String.Empty, ref luid, _PrivilegeName, ref _NameLength))
                {
                    return _PrivilegeName.ToString();
                }//if (Win32API.LookupPrivilegeName(String.Empty, ref luid, _PrivilegeName, ref _NameLength))
            }
            catch (Exception)
            {
                Console.WriteLine("## ERROR ## - Problem Getting Privilege Name!\nWin32 Error: '{0}', LUID '{1}'", Marshal.GetLastWin32Error(), luid);
            }//end of try-catch

            //default catch all
            return String.Empty;
        }
Beispiel #3
0
        public unsafe bool FindRun(Win32API.NONRESIDENT_ATTRIBUTE* attr, UInt64 vcn, ref UInt64 lcn, ref UInt64 count)
        {
            byte* run = null;
              lcn = 0;
              ulong baseoff = attr->LowVCN;

              if (vcn < attr->LowVCN || vcn > attr->HighVCN)
                    return false;

              for (run = (byte*)((byte*)(attr) + attr->RunArrayOffset); *run != 0; run += RunLength(run))
              {
                    lcn += RunLCN(run);
                    count = RunCount(run);

                    if (baseoff <= vcn && vcn < baseoff + count)
                    {
                          lcn = RunLCN(run) == 0 ? 0 : lcn + vcn - baseoff;
                          count -= (vcn - baseoff);
                          return true;
                    }
                    else
                          baseoff += count;
              }
              return false;
        }
        int IContextMenu.QueryContextMenu(Win32API.MenuHandler hMenu, uint iMenu, uint idCmdFirst, uint idCmdLast, CMF_UFlags uFlags)
        {
            InitMenuCommand();

            int id = 0;
            if ((uFlags & (CMF_UFlags.VerbsOnly | CMF_UFlags.DefaultOnly | CMF_UFlags.Noverbs)) == 0 ||
                (uFlags & CMF_UFlags.Explore) != 0)
            {
                //创建子菜单
                Win32API.MenuHandler submenu = Win32API.Win32.CreatePopupMenu();

                //添加菜单名称
                foreach(KeyValuePair<int,IContextMenuCommand> pair in commandDictionary)
                    Win32.AppendMenu(submenu, MF_UFlags.String, new IntPtr(idCmdFirst + id++), pair.Value.Name);

                //将子菜单插入到上下文菜单中
                Win32.InsertMenu(hMenu, 1, MF_UFlags.ByPosition | MF_UFlags.Popup, submenu.handle, "扩展工具集(&Y)");

                //为菜单增加图标
                Win32.SetMenuItemBitmaps(hMenu, 1, MF_UFlags.ByPosition, Properties.Resource.Main.GetHbitmap(), Properties.Resource.Main.GetHbitmap());

                foreach (KeyValuePair<int, IContextMenuCommand> pair in commandDictionary)
                {
                    if(pair.Value.HBitmap != IntPtr.Zero)
                        Win32.SetMenuItemBitmaps(submenu, pair.Key, MF_UFlags.ByPosition, pair.Value.HBitmap, pair.Value.HBitmap);
                }
            }
            return id;
        }
Beispiel #5
0
        public Win32API.SCROLLINFO GetScrollBarInfo(Win32API.ScrollBarTypes scrollBarType)
        {
            Win32API.SCROLLINFO scrollInfo = new Win32API.SCROLLINFO();
            scrollInfo.cbSize = (uint)Marshal.SizeOf(scrollInfo);
            scrollInfo.fMask = (uint)Win32API.ScrollInfoMask.SIF_ALL;

            Win32API.GetScrollInfo(this.currentWindowHandle, (int)scrollBarType, ref scrollInfo);

            return scrollInfo;
        }
Beispiel #6
0
        public unsafe void FixupUpdateSequenceArray(Win32API.FILE_RECORD_HEADER* file)
        {
            //ulong i = 0;
            //ushort* usa = (ushort*)((byte*)(file)+file->Ntfs.UsaOffset);
            //ushort* sector = (ushort*)(file);

            //for (i = 1; i < file->Ntfs.UsaCount; i++){
            //    sector[255] = usa[i];
            //    sector += 256;
            //}
        }
Beispiel #7
0
        /// <summary>
        /// Gets The System LUID Value for The Specified Privilege
        /// </summary>
        /// <param name="privilege">Specified Privilege</param>
        /// <returns>Associated LUID Value</returns>
        public static Win32API.LUID GetLUIDFromPrivilageName(Win32API.Privilege privilege)
        {
            Win32API.LUID _LUID = new Win32API.LUID();

            if (Win32API.LookupPrivilegeValue(String.Empty, privilege.ToString(), out _LUID) == false)
            {
                Console.WriteLine("## ERROR ## - Problem Resolving Privilage '{0}' To Its LUID!\nWin32 Error: '{1}'", privilege, Marshal.GetLastWin32Error());

                return new Win32API.LUID();
            }

            return _LUID;
        }
Beispiel #8
0
 private  void JudgeKeyevent(ref Win32API.KeyEvent keyEvent, string eventName)
 {
     if (eventName == KeyboardEvents.WM_KeyUp.ToString())
     {
         keyEvent.dwFlags = Win32API.KBEventFlag.KeyUp;
     }
     else if (eventName == KeyboardEvents.WM_KeyDown.ToString())
     {
         keyEvent.dwFlags = Win32API.KBEventFlag.KeyDown;
     }
     else
     {
         throw new InvalidOperationException("KeyEvent初始化失败");
     }
 }
Beispiel #9
0
 private  void JudgeKeyevent(ref Win32API.KeyEvent keyEvent, string eventName)
 {
     if (eventName == KeyboardEvents.WM_KeyUp.ToString())
     {
         keyEvent.dwFlags = Win32API.KBEventFlag.KeyUp;
     }
     else if (eventName == KeyboardEvents.WM_KeyDown.ToString())
     {
         keyEvent.dwFlags = Win32API.KBEventFlag.KeyDown;
     }
     else
     {
         //throw new Exception();
     }
 }
Beispiel #10
0
 public unsafe Win32API.RECORD_ATTRIBUTE* FindAttribute(Win32API.FILE_RECORD_HEADER* file, 
     Win32API.AttributeType type,
     string name)
 {
     Win32API.RECORD_ATTRIBUTE* attr=null;
     //for (attr = (Win32API.RECORD_ATTRIBUTE*)((byte*)file + file->AttributesOffset);
     //    (int)attr->AttributeType != -1;
     //    attr = (Win32API.RECORD_ATTRIBUTE*)((byte*)attr + attr->Length)) {
     for (attr = (Win32API.RECORD_ATTRIBUTE*)((byte*)(file) + file->AttributesOffset);
         (int)attr->AttributeType != -1;
         attr = (Win32API.RECORD_ATTRIBUTE*)((byte*)(attr) + attr->Length)) {
         if (attr->AttributeType == type) {
             if (name == null && attr->NameLength == 0)
                 return attr;
         }
     }
     return attr;
 }
Beispiel #11
0
 private  void JudgeMouseevent(XElement item, ref Win32API.MouseEvent mouseEvent)
 {
     string eventName = (string)(item.Element("MouseEvent").Value);
     switch (eventName)
     {
         case "WM_MOUSEMOVE":
             mouseEvent.dwFlags = Win32API.MouseEventFlag.Move;
             break;
         case "WM_LBUTTONDOWN":
             mouseEvent.dwFlags = Win32API.MouseEventFlag.LeftDown;
             break;
         case "WM_LBUTTONUP":
             mouseEvent.dwFlags = Win32API.MouseEventFlag.LeftUp;
             break;
         case "WM_LBUTTONDBLCLK":
             //MouseEvent.dwFlags  = Win32API.MouseEventFlag
             break;
         case "WM_RBUTTONDOWN":
             mouseEvent.dwFlags = Win32API.MouseEventFlag.RightDown;
             break;
         case "WM_RBUTTONUP":
             mouseEvent.dwFlags = Win32API.MouseEventFlag.RightUp;
             break;
         case "WM_RBUTTONDBLCLK":
             break;
         case "WM_MBUTTONDOWN":
             mouseEvent.dwFlags = Win32API.MouseEventFlag.MiddleDown;
             break;
         case "WM_MBUTTONUP":
             mouseEvent.dwFlags = Win32API.MouseEventFlag.MiddleUp;
             break;
         case "WM_MBUTTONDBLCLK":
             break;
         case "WM_MOUSEWHEEL":
             mouseEvent.dwFlags = Win32API.MouseEventFlag.Wheel;
             break;
         default:
             break;
     }
 }
Beispiel #12
0
        /// <summary>
        /// Helper routine to get a DateTime from a FILETIME.
        /// </summary>
        /// <param name="ft"></param>
        /// <returns></returns>
        public static DateTime FromFileTime( Win32API.FILETIME ft )
        {
            if( ft.dwHighDateTime == Int32.MaxValue || (ft.dwLowDateTime == 0 && ft.dwHighDateTime == 0) )
            {
                // Not going to fit in the DateTime.  In the WinInet APIs, this is
                // what happens when there is no FILETIME attached to the cache entry.
                // We're going to use DateTime.MinValue as a marker for this case.
                return DateTime.MinValue;
            }

            Win32API.SYSTEMTIME syst = new Win32API.SYSTEMTIME();
            Win32API.SYSTEMTIME systLocal = new Win32API.SYSTEMTIME();
            if( 0 == Win32API.FileTimeToSystemTime( ref ft, ref syst ) )
            {
                throw new ApplicationException( "Error calling FileTimeToSystemTime: " + Marshal.GetLastWin32Error() );
            }
            if( 0 == Win32API.SystemTimeToTzSpecificLocalTime( IntPtr.Zero, ref syst, out systLocal ) )
            {
                throw new ApplicationException( "Error calling SystemTimeToTzSpecificLocalTime: " + Marshal.GetLastWin32Error() );
            }

            return new DateTime( systLocal.Year, systLocal.Month, systLocal.Day, systLocal.Hour, systLocal.Minute, systLocal.Second );
        }
Beispiel #13
0
        private object HandleMenuMessage(Dictionary <string, object> message, DisposableDictionary table)
        {
            switch (message.Get("Arguments", ""))
            {
            case "LoadContextMenu":
                var contextMenuResponse = new ValueSet();
                var filePath            = (string)message["FilePath"];
                var extendedMenu        = (bool)message["ExtendedMenu"];
                var showOpenMenu        = (bool)message["ShowOpenMenu"];
                var split     = filePath.Split('|').Where(x => !string.IsNullOrWhiteSpace(x));
                var cMenuLoad = ContextMenu.GetContextMenuForFiles(split.ToArray(),
                                                                   (extendedMenu ? Shell32.CMF.CMF_EXTENDEDVERBS : Shell32.CMF.CMF_NORMAL) | Shell32.CMF.CMF_SYNCCASCADEMENU, FilterMenuItems(showOpenMenu));
                table.SetValue("MENU", cMenuLoad);
                return(cMenuLoad);

            case "ExecAndCloseContextMenu":
                var cMenuExec = table.GetValue <ContextMenu>("MENU");
                if (message.TryGetValue("ItemID", out var menuId))
                {
                    var isFont = new[] { ".fon", ".otf", ".ttc", ".ttf" }.Contains(Path.GetExtension(cMenuExec.ItemsPath[0]), StringComparer.OrdinalIgnoreCase);
                    var verb = message.Get("CommandString", (string)null);
                    switch (verb)
                    {
                    case string _ when verb == "install" && isFont:
                    {
                        var userFontDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft", "Windows", "Fonts");
                        var destName    = Path.Combine(userFontDir, Path.GetFileName(cMenuExec.ItemsPath[0]));
                        Win32API.RunPowershellCommand($"-command \"Copy-Item '{cMenuExec.ItemsPath[0]}' '{userFontDir}'; New-ItemProperty -Name '{Path.GetFileNameWithoutExtension(cMenuExec.ItemsPath[0])}' -Path 'HKCU:\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts' -PropertyType string -Value '{destName}'\"", false);
                    }
                    break;

                    case string _ when verb == "installAllUsers" && isFont:
                    {
                        var winFontDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Fonts");
                        Win32API.RunPowershellCommand($"-command \"Copy-Item '{cMenuExec.ItemsPath[0]}' '{winFontDir}'; New-ItemProperty -Name '{Path.GetFileNameWithoutExtension(cMenuExec.ItemsPath[0])}' -Path 'HKLM:\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts' -PropertyType string -Value '{Path.GetFileName(cMenuExec.ItemsPath[0])}'\"", true);
                    }
                    break;

                    case string _ when verb == "mount":
                        var vhdPath = cMenuExec.ItemsPath[0];
                        Win32API.MountVhdDisk(vhdPath);
                        break;

                    case string _ when verb == "format":
                        var drivePath = cMenuExec.ItemsPath[0];
                        Win32API.OpenFormatDriveDialog(drivePath);
                        break;

                    default:
                        cMenuExec?.InvokeItem((int)(long)menuId);
                        break;
                    }
                }
                // The following line is needed to cleanup resources when menu is closed.
                // Unfortunately if you uncomment it some menu items will randomly stop working.
                // Resource cleanup is currently done on app closing,
                // if we find a solution for the issue above, we should cleanup as soon as a menu is closed.
                //table.RemoveValue("MENU");
                return(null);

            default:
                return(null);
            }
        }
Beispiel #14
0
        private readonly int _headerSize = DirectAccess.SizeOf <RAWINPUTHEADER>();              // Size of the input data in bytes.
        #endregion

        #region IMessageFilter Members
        /// <summary>
        /// Filters out a message before it is dispatched.
        /// </summary>
        /// <param name="m">The message to be dispatched. You cannot modify this message.</param>
        /// <returns>
        /// true to filter the message and stop it from being dispatched; false to allow the message to continue to the next filter or control.
        /// </returns>
        public unsafe bool PreFilterMessage(ref Message m)
        {
            int dataSize = 0;

            // Get data size.
            int result = Win32API.GetRawInputData(m.LParam, RawInputCommand.Input, IntPtr.Zero, ref dataSize, _headerSize);

            if (result == -1)
            {
                throw new GorgonException(GorgonResult.CannotRead, Resources.GORINP_RAW_CANNOT_READ_DATA);
            }

            // Get actual data.
            var rawInputPtr = stackalloc byte[dataSize];

            result = Win32API.GetRawInputData(m.LParam,
                                              RawInputCommand.Input,
                                              (IntPtr)rawInputPtr,
                                              ref dataSize,
                                              _headerSize);

            if ((result == -1) ||
                (result != dataSize))
            {
                throw new GorgonException(GorgonResult.CannotRead, Resources.GORINP_RAW_CANNOT_READ_DATA);
            }

            var rawInput = *((RAWINPUT *)rawInputPtr);

            switch (rawInput.Header.Type)
            {
            case RawInputType.Mouse:
                if (RawInputPointingDeviceData != null)
                {
                    RawInputPointingDeviceData(this,
                                               new RawInputPointingDeviceEventArgs(rawInput.Header.Device,
                                                                                   ref rawInput.Union.Mouse));
                }
                break;

            case RawInputType.Keyboard:
                if (RawInputKeyboardData != null)
                {
                    RawInputKeyboardData(this,
                                         new RawInputKeyboardEventArgs(rawInput.Header.Device,
                                                                       ref rawInput.Union.Keyboard));
                }
                break;

            default:
                if (RawInputHIDData != null)
                {
                    var HIDData    = new byte[rawInput.Union.HID.Size * rawInput.Union.HID.Count];
                    var hidDataPtr = rawInputPtr + _headerSize + 8;

                    fixed(byte *buffer = &HIDData[0])
                    {
                        DirectAccess.MemoryCopy(buffer, hidDataPtr, HIDData.Length);
                    }

                    RawInputHIDData(this,
                                    new RawInputHIDEventArgs(rawInput.Header.Device, ref rawInput.Union.HID, HIDData));
                }
                break;
            }

            return(false);
        }
Beispiel #15
0
        public static bool KillMutex(Process process, string mutexType, string mutexName, bool partial)
        {
            Log(string.Format("Attempting to kill mutex"));
            // 4 tries
            for (int i = 1; i < 4; i++)
            {
                Log("Attempt #" + i);
                Console.WriteLine("Loop " + i);

                if (partial)
                {
                    var handles = Win32Processes.GetHandles(process, mutexType);
                    foreach (var handle in handles)
                    {
                        string strObjectName = Win32Processes.getObjectName(handle, Process.GetProcessById(handle.ProcessID));

                        if (!string.IsNullOrWhiteSpace(strObjectName) && strObjectName.Contains(mutexName))
                        {
                            Log(string.Format("Killing mutex located at '{0}'", strObjectName));
                            IntPtr ipHandle = IntPtr.Zero;
                            if (!Win32API.DuplicateHandle(Process.GetProcessById(handle.ProcessID).Handle, handle.Handle, Win32API.GetCurrentProcess(), out ipHandle, 0, false, Win32API.DUPLICATE_CLOSE_SOURCE))
                            {
                                Log(string.Format("DuplicateHandle() failed, error = {0}", Marshal.GetLastWin32Error()));
                                Console.WriteLine("DuplicateHandle() failed, error = {0}", Marshal.GetLastWin32Error());
                            }
                            else
                            {
                                Log("Mutex was killed successfully");
                                return(true);
                            }
                        }
                        //Log("----------------END-----------------");
                    }
                    return(true);
                }
                else
                {
                    var handles = Win32Processes.GetHandles(process, mutexType, "", mutexName);

                    if (handles.Count == 0)
                    {
                        Log(string.Format("{0} not found in process handles", mutexName));
                        continue;
                    }

                    foreach (var handle in handles)
                    {
                        string strObjectName = Win32Processes.getObjectName(handle, Process.GetProcessById(handle.ProcessID));
                        Log(string.Format("Killing mutex {0}", strObjectName));
                        if (!string.IsNullOrWhiteSpace(strObjectName) && strObjectName.EndsWith(mutexName))
                        {
                            IntPtr ipHandle = IntPtr.Zero;
                            if (!Win32API.DuplicateHandle(Process.GetProcessById(handle.ProcessID).Handle, handle.Handle, Win32API.GetCurrentProcess(), out ipHandle, 0, false, Win32API.DUPLICATE_CLOSE_SOURCE))
                            {
                                Console.WriteLine("DuplicateHandle() failed, error = {0}", Marshal.GetLastWin32Error());
                            }
                            else
                            {
                                Log("Mutex was killed successfully");
                                return(true);
                            }
                        }
                    }
                }
            }
            Log("Mutex was not killed");
            //Log("----------------END-----------------");
            return(false);
        }
Beispiel #16
0
 /// <summary>
 /// The input callback for midiOutOpen.
 /// </summary>
 private void InputCallback(Win32API.HMIDIIN hMidiIn, Win32API.MidiInMessage wMsg,
     UIntPtr dwInstance, UIntPtr dwParam1, UIntPtr dwParam2)
 {
     isInsideInputHandler = true;
     try
     {
         if (wMsg == Win32API.MidiInMessage.MIM_DATA)
         {
             Channel channel;
             Pitch pitch;
             int velocity;
             Control control;
             int value;
             Instrument instrument;
             UInt32 win32Timestamp;
             if (ShortMsg.IsNoteOn(dwParam1, dwParam2))
             {
                 if (NoteOn != null)
                 {
                     ShortMsg.DecodeNoteOn(dwParam1, dwParam2, out channel, out pitch,
                         out velocity, out win32Timestamp);
                     NoteOn(new NoteOnMessage(this, channel, pitch, velocity,
                         clock == null ? win32Timestamp/1000f : clock.Time));
                 }
             }
             else if (ShortMsg.IsNoteOff(dwParam1, dwParam2))
             {
                 if (NoteOff != null)
                 {
                     ShortMsg.DecodeNoteOff(dwParam1, dwParam2, out channel, out pitch,
                         out velocity, out win32Timestamp);
                     NoteOff(new NoteOffMessage(this, channel, pitch, velocity,
                         clock == null ? win32Timestamp / 1000f : clock.Time));
                 }
             }
             else if (ShortMsg.IsControlChange(dwParam1, dwParam2))
             {
                 if (ControlChange != null)
                 {
                     ShortMsg.DecodeControlChange(dwParam1, dwParam2, out channel,
                         out control, out value, out win32Timestamp);
                     ControlChange(new ControlChangeMessage(this, channel, control, value,
                         clock == null ? win32Timestamp / 1000f : clock.Time));
                 }
             }
             else if (ShortMsg.IsProgramChange(dwParam1, dwParam2))
             {
                 if (ProgramChange != null)
                 {
                     ShortMsg.DecodeProgramChange(dwParam1, dwParam2, out channel,
                         out instrument, out win32Timestamp);
                     ProgramChange(new ProgramChangeMessage(this, channel, instrument,
                         clock == null ? win32Timestamp / 1000f : clock.Time));
                 }
             }
             else if (ShortMsg.IsPitchBend(dwParam1, dwParam2))
             {
                 if (PitchBend != null)
                 {
                     ShortMsg.DecodePitchBend(dwParam1, dwParam2, out channel,
                         out value, out win32Timestamp);
                     PitchBend(new PitchBendMessage(this, channel, value,
                         clock == null ? win32Timestamp / 1000f : clock.Time));
                 }
             }
             else
             {
                 // Unsupported messages are ignored.
             }
         }
     }
     finally
     {
         isInsideInputHandler = false;
     }
 }
 private void btnGetForm_Click(object sender, EventArgs e)
 {
     int i = 0;
     cbxFrom.Items.Clear();
     Win32API api2 = new Win32API();
     CallBack myCallBack = new CallBack(api2.Report);
     Win32API.EnumWindows(myCallBack, 0);
     while (!string.IsNullOrEmpty(Win32API.GroupNames[i]))
     {
         //GName.Add(win32Normal.GroupNames[i++]);
         cbxFrom.Items.Add(Win32API.GroupNames[i++]);
     }
     //labelGroupName.Text = GName[++GNum < GName.Count ? GNum : (GNum = 0)].ToString();
     cbxFrom .Text = cbxFrom.Items[0].ToString();
 }
Beispiel #18
0
 public static void RestoreHighLight(Win32API.Rect rect, IntPtr handle)
 {
     Win32API.Rect invalidRect = new Win32API.Rect();
     invalidRect.left = rect.left - Hight_Border;
     invalidRect.top = rect.top - Hight_Border;
     invalidRect.right = rect.right + Hight_Border;
     invalidRect.bottom = rect.bottom + Hight_Border;
     //refresh the window
     Win32API.InvalidateRect(handle, ref invalidRect, 1);
     //Win32API.UpdateWindow(handle);
 }
 public Win32_WTSSession(string workstation, Int32 session, Win32API.WTS_CONNECTSTATE_CLASS state)
 {
     WorkstationName = workstation;
     SessionID = session;
     State = state;
 }
Beispiel #20
0
        private void button44_Click(object sender, EventArgs e)
        {
            bool result = Win32API.SetWindowText(this.Handle, "SetWindowText");

            Console.WriteLine(result);
        }
Beispiel #21
0
        private void button45_Click(object sender, EventArgs e)
        {
            bool result = Win32API.ShowOwnedPopups(this.Handle, false);

            Console.WriteLine(result);
        }
Beispiel #22
0
        private void button1_Click(object sender, EventArgs e)
        {
            bool b = Win32API.ShowWindow((IntPtr)0x00100A2, ShowWindowCmd.SW_SHOW);

            Console.WriteLine(b);
        }
Beispiel #23
0
 private void button43_Click(object sender, EventArgs e)
 {
     Win32API.SetWindowPos(this.Handle, IntPtr.Zero, 0, 0, 0, 0, WindowPosFlag.SWP_NOSIZE);
     System.Threading.Thread.Sleep(2 * 1000);
     Win32API.SetWindowPos(this.Handle, IntPtr.Zero, 100, 100, 500, 350, WindowPosFlag.SWP_NOMOVE);
 }
Beispiel #24
0
 private void button41_Click(object sender, EventArgs e)
 {
     Win32API.SetClassLong(this.Handle, ClassLongIndex.GCL_STYLE, 00000188);
 }
Beispiel #25
0
        private void button40_Click(object sender, EventArgs e)
        {
            int result = Win32API.GetWindowLong((IntPtr)0x000100A2, WindowLongIndex.GWL_STYLE);

            Console.WriteLine(result);
        }
Beispiel #26
0
        public static string getObjectName(Win32API.SYSTEM_HANDLE_INFORMATION shHandle, Process process)
        {
            IntPtr m_ipProcessHwnd = Win32API.OpenProcess(Win32API.ProcessAccessFlags.All, false, process.Id);
            IntPtr ipHandle = IntPtr.Zero;
            var objBasic = new Win32API.OBJECT_BASIC_INFORMATION();
            IntPtr ipBasic = IntPtr.Zero;
            IntPtr ipObjectType = IntPtr.Zero;
            var objObjectName = new Win32API.OBJECT_NAME_INFORMATION();
            IntPtr ipObjectName = IntPtr.Zero;
            string strObjectName = "";
            int nLength = 0;
            int nReturn = 0;
            IntPtr ipTemp = IntPtr.Zero;

            if (!Win32API.DuplicateHandle(m_ipProcessHwnd, shHandle.Handle, Win32API.GetCurrentProcess(),
                                          out ipHandle, 0, false, Win32API.DUPLICATE_SAME_ACCESS))
                return null;

            ipBasic = Marshal.AllocHGlobal(Marshal.SizeOf(objBasic));
            Win32API.NtQueryObject(ipHandle, (int)Win32API.ObjectInformationClass.ObjectBasicInformation,
                                   ipBasic, Marshal.SizeOf(objBasic), ref nLength);
            objBasic = (Win32API.OBJECT_BASIC_INFORMATION)Marshal.PtrToStructure(ipBasic, objBasic.GetType());
            Marshal.FreeHGlobal(ipBasic);


            nLength = objBasic.NameInformationLength;

            ipObjectName = Marshal.AllocHGlobal(nLength);
            while ((uint)(nReturn = Win32API.NtQueryObject(
                     ipHandle, (int)Win32API.ObjectInformationClass.ObjectNameInformation,
                     ipObjectName, nLength, ref nLength))
                   == Win32API.STATUS_INFO_LENGTH_MISMATCH)
            {
                Marshal.FreeHGlobal(ipObjectName);
                ipObjectName = Marshal.AllocHGlobal(nLength);
            }
            objObjectName = (Win32API.OBJECT_NAME_INFORMATION)Marshal.PtrToStructure(ipObjectName, objObjectName.GetType());

            if (Is64Bits())
            {
                ipTemp = new IntPtr(Convert.ToInt64(objObjectName.Name.Buffer.ToString(), 10) >> 32);
            }
            else
            {
                ipTemp = objObjectName.Name.Buffer;
            }

            if (ipTemp != IntPtr.Zero)
            {

                byte[] baTemp2 = new byte[nLength];
                try
                {
                    Marshal.Copy(ipTemp, baTemp2, 0, nLength);

                    strObjectName = Marshal.PtrToStringUni(Is64Bits() ?
                                                           new IntPtr(ipTemp.ToInt64()) :
                                                           new IntPtr(ipTemp.ToInt32()));
                    return strObjectName;
                }
                catch (AccessViolationException)
                {
                    return null;
                }
                finally
                {
                    Marshal.FreeHGlobal(ipObjectName);
                    Win32API.CloseHandle(ipHandle);
                }
            }
            return null;
        }
Beispiel #27
0
 public override void LoadSettings()
 {
     base.LoadSettings("pictures", Win32API.GetFolderPath(Win32API.CSIDL_MYPICTURES));
 }
Beispiel #28
0
        private void button46_Click(object sender, EventArgs e)
        {
            bool result = Win32API.ShowWindowAsync((IntPtr)0x0006041E, ShowWindowCmd.SW_HIDE);

            Console.WriteLine(result);
        }
 /// <summary>
 /// Hides Taskbar.
 /// </summary>
 public static void Hide()
 {
     Win32API.ShowWindow(Handle, 0);
 }
Beispiel #30
0
        private void button49_Click(object sender, EventArgs e)
        {
            bool result = Win32API.AnyPopup();

            Console.WriteLine(result);
        }
Beispiel #31
0
        public static Win32API/*!*/ Reinitialize(
            ConversionStorage<MutableString>/*!*/ toStr,
            Win32API/*!*/ self,
            [DefaultProtocol, NotNull]MutableString/*!*/ libraryName,
            [DefaultProtocol, NotNull]MutableString/*!*/ functionName,
            [NotNull]IList/*!*/ parameterTypes,
            [DefaultProtocol, NotNull]MutableString/*!*/ returnType) {

            return self.Reinitialize(
                GetFunction(libraryName, functionName),
                MakeSignature(parameterTypes.Count, (i) => {
                    var str = Protocols.CastToString(toStr, parameterTypes[i]);
                    return str.IsEmpty ? (byte)0 : str.GetByte(0);
                }),
                returnType.IsEmpty ? ArgType.None : ToArgType(returnType.GetByte(0))
            );
        }
Beispiel #32
0
        private void button52_Click(object sender, EventArgs e)
        {
            uint result = Win32API.GetClassLong(this.Handle, ClassLongIndex.GCL_WNDPROC);

            Console.WriteLine(result);
        }
Beispiel #33
0
        /// <summary>
        /// The input callback for midiOutOpen.
        /// </summary>
        private void InputCallback(Win32API.HMIDIIN hMidiIn, Win32API.MidiInMessage wMsg,
            UIntPtr dwInstance, UIntPtr dwParam1, UIntPtr dwParam2)
        {
            isInsideInputHandler = true;
            try
            {
                if (wMsg == Win32API.MidiInMessage.MIM_DATA)
                {
                    Channel channel;
                    Pitch pitch;
                    int velocity;
                    Control control;
                    int value;
                    Instrument instrument;
                    UInt32 win32Timestamp;
                    if (ShortMsg.IsNoteOn(dwParam1, dwParam2))
                    {
                        if (NoteOn != null)
                        {
                            ShortMsg.DecodeNoteOn(dwParam1, dwParam2, out channel, out pitch,
                                out velocity, out win32Timestamp);
                            NoteOn(new NoteOnMessage(this, channel, pitch, velocity,
                                clock == null ? win32Timestamp/1000f : clock.Time));
                        }
                    }
                    else if (ShortMsg.IsNoteOff(dwParam1, dwParam2))
                    {
                        if (NoteOff != null)
                        {
                            ShortMsg.DecodeNoteOff(dwParam1, dwParam2, out channel, out pitch,
                                out velocity, out win32Timestamp);
                            NoteOff(new NoteOffMessage(this, channel, pitch, velocity,
                                clock == null ? win32Timestamp / 1000f : clock.Time));
                        }
                    }
                    else if (ShortMsg.IsControlChange(dwParam1, dwParam2))
                    {
                        if (ControlChange != null)
                        {
                            ShortMsg.DecodeControlChange(dwParam1, dwParam2, out channel,
                                out control, out value, out win32Timestamp);
                            ControlChange(new ControlChangeMessage(this, channel, control, value,
                                clock == null ? win32Timestamp / 1000f : clock.Time));
                        }
                    }
                    else if (ShortMsg.IsProgramChange(dwParam1, dwParam2))
                    {
                        if (ProgramChange != null)
                        {
                            ShortMsg.DecodeProgramChange(dwParam1, dwParam2, out channel,
                                out instrument, out win32Timestamp);
                            ProgramChange(new ProgramChangeMessage(this, channel, instrument,
                                clock == null ? win32Timestamp / 1000f : clock.Time));
                        }
                    }
                    else if (ShortMsg.IsPitchBend(dwParam1, dwParam2))
                    {
                        if (PitchBend != null)
                        {
                            ShortMsg.DecodePitchBend(dwParam1, dwParam2, out channel,
                                out value, out win32Timestamp);
                            PitchBend(new PitchBendMessage(this, channel, value,
                                clock == null ? win32Timestamp / 1000f : clock.Time));
                        }
                    }
                    else
                    {
                        // Unsupported messages are ignored.
                    }
                }
            #region SysEx
                else if (wMsg == Win32API.MidiInMessage.MIM_LONGDATA)
                {
                    Byte[] data;
                    UInt32 win32Timestamp;
                    if (LongMsg.IsSysEx(dwParam1, dwParam2))
                    {
                        if (SysEx != null)
                        {
                            LongMsg.DecodeSysEx(dwParam1, dwParam2, out data, out win32Timestamp);
                            if (data.Length != 0)
                            {
                                SysEx(new SysExMessage(this, data, clock == null ? win32Timestamp / 1000f : clock.Time));
                            }

                            if (isClosing)
                            {
                                //buffers no longer needed
                                DestroyLongMsgBuffer(dwParam1);
                            }
                            else
                            {
                                //prepare the buffer for the next message
                                RecycleLongMsgBuffer(dwParam1);
                            }
                        }
                    }
                }
                // The rest of these are just for long message testing
                else if (wMsg == Win32API.MidiInMessage.MIM_MOREDATA)
                {
                    SysEx(new SysExMessage(this, new byte[] { 0x13 }, 13));
                }
                else if (wMsg == Win32API.MidiInMessage.MIM_OPEN)
                {
                    //SysEx(new SysExMessage(this, new byte[] { 0x01 }, 1));
                }
                else if (wMsg == Win32API.MidiInMessage.MIM_CLOSE)
                {
                    //SysEx(new SysExMessage(this, new byte[] { 0x02 }, 2));
                }
                else if (wMsg == Win32API.MidiInMessage.MIM_ERROR)
                {
                    SysEx(new SysExMessage(this, new byte[] { 0x03 }, 3));
                }
                else if (wMsg == Win32API.MidiInMessage.MIM_LONGERROR)
                {
                    SysEx(new SysExMessage(this, new byte[] { 0x04 }, 4));
                }
                else
                {
                    SysEx(new SysExMessage(this, new byte[] { 0x05 }, 5));
                }
            #endregion
            }
            finally
            {
                isInsideInputHandler = false;
            }
        }
Beispiel #34
0
        private void button53_Click(object sender, EventArgs e)
        {
            ushort result = Win32API.GetClassWord(this.Handle, ClassLongIndex.GCL_HICON);

            Console.Write(result);
        }
Beispiel #35
0
        /// <summary>
        /// Get a string representation of the given FILETIME.
        /// </summary>
        /// <param name="ft"></param>
        /// <returns></returns>
        public static string ToStringFromFileTime( Win32API.FILETIME ft )
        {
            DateTime dt = FromFileTime( ft );
            if( dt == DateTime.MinValue )
            {
                return "";
            }

            return dt.ToString();
        }
Beispiel #36
0
        private void button57_Click(object sender, EventArgs e)
        {
            bool result = Win32API.SendNotifyMessage(this.Handle, WindowsMsg.WM_DESTROY, (IntPtr)1, (IntPtr)0);

            Console.WriteLine(result);
        }
 static extern bool ShellExecuteEx(ref Win32API.Shell32.SHELLEXECUTEINFO lpExecInfo);
Beispiel #38
0
        private void button58_Click(object sender, EventArgs e)
        {
            IntPtr result = Win32API.GetMessageExtraInfo();

            Console.WriteLine(result);
        }
 public IconHelper(string icon_path, int idx)
 {
     path  = icon_path;
     index = idx;
     Value = Win32API.ExtractIcon(path, index, true);
 }
Beispiel #40
0
 private void button61_Click(object sender, EventArgs e)
 {
     Button btn    = (Button)sender;
     int    ID     = Win32API.GetDlgCtrlID(button1.Handle);
     bool   result = Win32API.CheckDlgButton(this.Handle, ID, BtnState.BST_INDETERMINATE);
 }
Beispiel #41
0
        public async Task ParseArgumentsAsync(PipeStream connection, Dictionary <string, object> message, string arguments)
        {
            switch (arguments)
            {
            case "LoadContextMenu":
                var contextMenuResponse        = new ValueSet();
                var loadThreadWithMessageQueue = new ThreadWithMessageQueue <Dictionary <string, object> >(HandleMenuMessage);
                var cMenuLoad = await loadThreadWithMessageQueue.PostMessageAsync <ContextMenu>(message);

                contextMenuResponse.Add("Handle", handleTable.AddValue(loadThreadWithMessageQueue));
                contextMenuResponse.Add("ContextMenu", JsonConvert.SerializeObject(cMenuLoad));
                await Win32API.SendMessageAsync(connection, contextMenuResponse, message.Get("RequestID", (string)null));

                break;

            case "ExecAndCloseContextMenu":
                var menuKey = (string)message["Handle"];
                var execThreadWithMessageQueue = handleTable.GetValue <ThreadWithMessageQueue <Dictionary <string, object> > >(menuKey);
                if (execThreadWithMessageQueue != null)
                {
                    await execThreadWithMessageQueue.PostMessage(message);
                }
                // The following line is needed to cleanup resources when menu is closed.
                // Unfortunately if you uncomment it some menu items will randomly stop working.
                // Resource cleanup is currently done on app closing,
                // if we find a solution for the issue above, we should cleanup as soon as a menu is closed.
                //handleTable.RemoveValue(menuKey);
                break;

            case "InvokeVerb":
                var filePath = (string)message["FilePath"];
                var split    = filePath.Split('|').Where(x => !string.IsNullOrWhiteSpace(x));
                var verb     = (string)message["Verb"];
                using (var cMenu = ContextMenu.GetContextMenuForFiles(split.ToArray(), Shell32.CMF.CMF_DEFAULTONLY))
                {
                    var result = cMenu?.InvokeVerb(verb);
                    await Win32API.SendMessageAsync(connection, new ValueSet()
                    {
                        { "Success", result }
                    }, message.Get("RequestID", (string)null));
                }
                break;

            case "GetNewContextMenuEntries":
                var entries = await SafetyExtensions.IgnoreExceptions(() => ShellNewMenuHelper.GetNewContextMenuEntries(), Program.Logger);

                await Win32API.SendMessageAsync(connection, new ValueSet()
                {
                    { "Entries", JsonConvert.SerializeObject(entries) }
                }, message.Get("RequestID", (string)null));

                break;

            case "GetNewContextMenuEntryForType":
                var fileExtension = (string)message["extension"];
                var entry         = await SafetyExtensions.IgnoreExceptions(() => ShellNewMenuHelper.GetNewContextMenuEntryForType(fileExtension), Program.Logger);

                await Win32API.SendMessageAsync(connection, new ValueSet()
                {
                    { "Entry", JsonConvert.SerializeObject(entry) }
                }, message.Get("RequestID", (string)null));

                break;
            }
        }
Beispiel #42
0
        private void button63_Click(object sender, EventArgs e)
        {
            int result = Win32API.GetSystemMetrics(SysMetericsIndex.SM_CYCAPTION);

            Console.WriteLine(result);
        }
        int IContextMenu.QueryContextMenu(Win32API.MenuHandler hMenu, uint iMenu, uint idCmdFirst, uint idCmdLast, CMF_UFlags uFlags)
        {
            int id = 0;
            if ((uFlags & (CMF_UFlags.VerbsOnly | CMF_UFlags.DefaultOnly | CMF_UFlags.Noverbs)) == 0 ||
                (uFlags & CMF_UFlags.Explore) != 0)
            {
                //创建子菜单
                Win32API.MenuHandler submenu = Win32API.Helpers.CreatePopupMenu();
                Helpers.AppendMenu(submenu, MF_UFlags.String, new IntPtr(idCmdFirst + id++), "删除 .svn(&S)");
                Helpers.AppendMenu(submenu, MF_UFlags.String, new IntPtr(idCmdFirst + id++), "删除 Thumbs.db(&T)");
                Helpers.AppendMenu(submenu, MF_UFlags.String, new IntPtr(idCmdFirst + id++), "批量重命名(&R)");
                Helpers.AppendMenu(submenu, MF_UFlags.String, new IntPtr(idCmdFirst + id++), "批量文本编码格式转换(&E)");
                Helpers.AppendMenu(submenu, MF_UFlags.String, new IntPtr(idCmdFirst + id++), "反馈: Dragon.Zhang(&M)");

                //将子菜单插入到上下文菜单中
                Helpers.InsertMenu(hMenu, 1, MF_UFlags.ByPosition | MF_UFlags.Popup, submenu.handle, "扩展工具集(&Y)");

                //为菜单增加图标
                Helpers.SetMenuItemBitmaps(hMenu, 1, MF_UFlags.ByPosition, Properties.Resource.Main.GetHbitmap(), Properties.Resource.Main.GetHbitmap());
                Helpers.SetMenuItemBitmaps(submenu, 0, MF_UFlags.ByPosition, Properties.Resource.DeleteFolder.GetHbitmap(), Properties.Resource.DeleteFolder.GetHbitmap());
                Helpers.SetMenuItemBitmaps(submenu, 1, MF_UFlags.ByPosition, Properties.Resource.DeleteFile.GetHbitmap(), Properties.Resource.DeleteFile.GetHbitmap());
                Helpers.SetMenuItemBitmaps(submenu, 3, MF_UFlags.ByPosition, Properties.Resource.EncodingConvert.GetHbitmap(), Properties.Resource.EncodingConvert.GetHbitmap());
                Helpers.SetMenuItemBitmaps(submenu, 4, MF_UFlags.ByPosition, Properties.Resource.MailTo.GetHbitmap(), Properties.Resource.MailTo.GetHbitmap());
            }
            return id;
        }
Beispiel #44
0
        private void button66_Click(object sender, EventArgs e)
        {
            bool result = Win32API.EndDialog((IntPtr)0x00020576, (IntPtr)1);

            Console.WriteLine(result);
        }
 /// <summary>
 /// Shows Taskbar.
 /// </summary>
 public static void Show()
 {
     Win32API.ShowWindow(Handle, 1);
 }
Beispiel #46
0
 public static extern bool EnumThreadWindows(uint dwThreadId, Win32API.EnumThreadDelegate lpfn, IntPtr lParam);
Beispiel #47
0
        public void SendAction(ToastifyAction action)
        {
            if (!this.IsRunning)
            {
                return;
            }

            bool sendAppCommandMessage = false;
            bool sendMediaKey          = false;

            switch (action)
            {
#if DEBUG
            case ToastifyAction.ShowDebugView:
#endif
            case ToastifyAction.None:
            case ToastifyAction.CopyTrackInfo:
            case ToastifyAction.PasteTrackInfo:
            case ToastifyAction.ThumbsUp:
            case ToastifyAction.ThumbsDown:
            case ToastifyAction.ShowToast:
            case ToastifyAction.SettingsSaved:
            case ToastifyAction.Exit:
                break;

            case ToastifyAction.ShowSpotify:
                Analytics.TrackEvent(Analytics.ToastifyEventCategory.Action, Analytics.ToastifyEvent.Action.ShowSpotify);
                if (this.IsMinimized)
                {
                    this.ShowSpotify();
                }
                else
                {
                    this.Minimize();
                }
                break;

            case ToastifyAction.VolumeUp:
                Analytics.TrackEvent(Analytics.ToastifyEventCategory.Action, Analytics.ToastifyEvent.Action.VolumeUp);
                switch ((ToastifyVolumeControlMode)Settings.Current.VolumeControlMode)
                {
                // The Spotify volume control mode has been dropped since Spotify version 1.0.75.483.g7ff4a0dc due to issue #31
                //case ToastifyVolumeControlMode.Spotify:
                //    this.SendShortcut(action);
                //    break;

                case ToastifyVolumeControlMode.SystemSpotifyOnly:
                    this.localAPI.IncrementVolume();
                    break;

                case ToastifyVolumeControlMode.SystemGlobal:
                    sendMediaKey = true;
                    break;

                default:
                    sendMediaKey = true;
                    break;
                }
                break;

            case ToastifyAction.VolumeDown:
                Analytics.TrackEvent(Analytics.ToastifyEventCategory.Action, Analytics.ToastifyEvent.Action.VolumeDown);
                switch ((ToastifyVolumeControlMode)Settings.Current.VolumeControlMode)
                {
                // The Spotify volume control mode has been dropped since Spotify version 1.0.75.483.g7ff4a0dc due to issue #31
                //case ToastifyVolumeControlMode.Spotify:
                //    this.SendShortcut(action);
                //    break;

                case ToastifyVolumeControlMode.SystemSpotifyOnly:
                    this.localAPI.DecrementVolume();
                    break;

                case ToastifyVolumeControlMode.SystemGlobal:
                default:
                    sendMediaKey = true;
                    break;
                }
                break;

            case ToastifyAction.Mute:
                Analytics.TrackEvent(Analytics.ToastifyEventCategory.Action, Analytics.ToastifyEvent.Action.Mute);
                switch ((ToastifyVolumeControlMode)Settings.Current.VolumeControlMode)
                {
                case ToastifyVolumeControlMode.SystemSpotifyOnly:
                    this.localAPI.ToggleMute();
                    break;

                // The Spotify volume control mode has been dropped since Spotify version 1.0.75.483.g7ff4a0dc due to issue #31
                //case ToastifyVolumeControlMode.Spotify:
                case ToastifyVolumeControlMode.SystemGlobal:
                default:
                    sendMediaKey = true;
                    break;
                }
                break;

            case ToastifyAction.FastForward:
            case ToastifyAction.Rewind:
            case ToastifyAction.PlayPause:
            case ToastifyAction.PreviousTrack:
            case ToastifyAction.NextTrack:
                goto default;

            default:
                Analytics.TrackEvent(Analytics.ToastifyEventCategory.Action, $"{Analytics.ToastifyEvent.Action.Default}{action}");
                sendAppCommandMessage = true;
                break;
            }

            if (sendAppCommandMessage)
            {
                Windows.SendAppCommandMessage(this.GetMainWindowHandle(), (IntPtr)action, true);
            }
            if (sendMediaKey)
            {
                Win32API.SendMediaKey(action);
            }
        }
Beispiel #48
0
 public FileApi(Win32API.SYSTEM_HANDLE_INFORMATION _sYSTEM_HANDLE_INFORMATION)
 {
     sYSTEM_HANDLE_INFORMATION = _sYSTEM_HANDLE_INFORMATION;
     _loadInfo();
 }
Beispiel #49
0
        public static Win32API/*!*/ Reinitialize(Win32API/*!*/ self,
            [DefaultProtocol, NotNull]MutableString/*!*/ libraryName,
            [DefaultProtocol, NotNull]MutableString/*!*/ functionName,
            [DefaultProtocol, NotNull]MutableString/*!*/ parameterTypes,
            [DefaultProtocol, NotNull]MutableString/*!*/ returnType) {

            return self.Reinitialize(
                GetFunction(libraryName, functionName),
                MakeSignature(parameterTypes.GetByteCount(), parameterTypes.GetByte),
                returnType.IsEmpty ? ArgType.None : ToArgType(returnType.GetByte(0))
            );
        }
Beispiel #50
0
        /// <summary>
        /// Executes the bot's awakening routine.
        /// </summary>
        /// <param name="preferredAwakes"></param>
        private void AwakeningLoopThread(List <Awake> preferredAwakes)
        {
            try
            {
                CrossThreadAppendLog("Bot has started\n");

                Win32API.SetForegroundWindow(Ui.Process.Handle);

                using (AwakeningResolver awakeResolver = new AwakeningResolver(ConfigManager, this))
                {
                    while (true)
                    {
                        Stopwatch stopWatch = new Stopwatch();
                        stopWatch.Start();

                        // Hover over the item to check the awake
                        BotHelper.SetCursorPosition(ItemPosition);

                        if (IsStopped())
                        {
                            break;
                        }

                        // Add specified delay to compensate for laggy server
                        int msValue = 0;

                        Ui.Invoke(new Action(() =>
                        {
                            msValue = Ui.trackBarMsDelay.Value;
                        }));

                        Thread.Sleep(msValue);

                        Bitmap bmp = awakeResolver.SnapshotRectangle(InventoryRectangle);

                        // bmp.Save("1.bmp");

                        Ui.Invoke(new Action(() =>
                        {
                            Ui.PictureBoxDebug1.Image = (Image)bmp.Clone();
                        }));

                        bmp = awakeResolver.DifferentiateAwakeText(bmp);
                        // bmp.Save("2.bmp");

                        Ui.Invoke(new Action(() =>
                        {
                            Ui.PictureBoxDebug2.Image = (Image)bmp.Clone();
                        }));

                        bmp = awakeResolver.CropBitmapSmart(bmp);
                        // bmp.Save("3.bmp");

                        Ui.Invoke(new Action(() =>
                        {
                            Ui.PictureBoxDebug3.Image = (Image)bmp.Clone();
                        }));

                        bmp = awakeResolver.IncreaseBitmapSize(bmp, 300);
                        // bmp.Save("4.bmp");

                        Ui.Invoke(new Action(() =>
                        {
                            Ui.PictureBoxDebug4.Image = (Image)bmp.Clone();
                        }));

                        string awakeText = awakeResolver.GetAwakening(bmp);

                        AwakeningParser awakeParser = new AwakeningParser(Ui, ConfigManager, awakeText);
                        List <Awake>    itemAwakes  = awakeParser.GetCompletedAwakes();

                        string awakeAchieved = "";

                        for (int i = 0; i < itemAwakes.Count; ++i)
                        {
                            awakeAchieved += itemAwakes[i].ToString() + (i == (itemAwakes.Count - 1) ? "" : " | ");
                        }

                        if (awakeAchieved.Length <= 0)
                        {
                            awakeAchieved = "No awake found\n";
                            CrossThreadAppendLog(awakeAchieved + "\n");
                        }

                        CrossThreadAppendLog(awakeAchieved + "\n");

                        // Check if awake meets the requirements
                        if (AwakeMeetsRequirements(itemAwakes, preferredAwakes))
                        {
                            CrossThreadAppendLog("Preferred awake was successfully achieved\n");

                            stopWatch.Stop();
                            CrossThreadChangeControlText(Ui.lblIterationTime, stopWatch.ElapsedMilliseconds.ToString() + " ms");
                            CrossThreadChangeControlText(Ui.lblTotalTries, (Convert.ToInt32(Ui.lblTotalTries.Text) + 1).ToString());

                            break;
                        }

                        CrossThreadAppendLog("Preferred awake was not achieved\n");

                        // Doubleclick reversion scroll
                        BotHelper.SimulateMouseClick(Ui.Process.Handle, ReversionPosition);
                        BotHelper.SimulateMouseClick(Ui.Process.Handle, ReversionPosition);

                        int ms = 200;

                        Thread.Sleep(ms);

                        // Click item with reversion
                        BotHelper.SimulateMouseClick(Ui.Process.Handle, ItemPosition);

                        // Wait until the reversion is done on the item
                        Thread.Sleep(ConfigManager.ScrollDelay);

                        // Doubleclick awake scroll
                        BotHelper.SimulateMouseClick(Ui.Process.Handle, AwakeScrollPosition);

                        if (!Ui.cbSupportAugmentation.Checked)
                        {
                            BotHelper.SimulateMouseClick(Ui.Process.Handle, AwakeScrollPosition);
                        }

                        Thread.Sleep(ms);

                        // Click item with awake scroll
                        BotHelper.SimulateMouseClick(Ui.Process.Handle, ItemPosition);

                        Thread.Sleep(ms);

                        BotHelper.SetCursorPosition(new Point(ItemPosition.X + 200, ItemPosition.Y + 200));
                        Thread.Sleep(ms);
                        BotHelper.SetCursorPosition(ItemPosition);

                        // Wait until the awake is done on the item
                        Thread.Sleep(ConfigManager.ScrollDelay);

                        bmp.Dispose();

                        if (IsStopped())
                        {
                            break;
                        }

                        stopWatch.Stop();
                        CrossThreadChangeControlText(Ui.lblIterationTime, stopWatch.ElapsedMilliseconds.ToString() + " ms");
                        CrossThreadChangeControlText(Ui.lblTotalTries, (Convert.ToInt32(Ui.lblTotalTries.Text) + 1).ToString());
                    }
                }

                CrossThreadChangeControlText(Ui.btnStartBot, "Start");

                CrossThreadAppendLog("Bot has finished\n");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Beispiel #51
0
 public static extern int InvalidateRect(IntPtr hWnd, ref Win32API.Rect lpRect, int bErase);
Beispiel #52
0
        public static bool KillMutex(Process process, string mutexName)
        {
            // 4 tries
            for (int i = 1; i < 4; i++)
            {
                Console.WriteLine("Loop " + i);
                var handles = Win32Processes.GetHandles(process, "Mutant", "\\Sessions\\", mutexName);
                if (handles.Count == 0)
                {
                    continue;
                }

                foreach (var handle in handles)
                {
                    IntPtr ipHandle = IntPtr.Zero;
                    if (!Win32API.DuplicateHandle(Process.GetProcessById(handle.ProcessID).Handle, handle.Handle, Win32API.GetCurrentProcess(), out ipHandle, 0, false, Win32API.DUPLICATE_CLOSE_SOURCE))
                    {
                        Console.WriteLine("DuplicateHandle() failed, error = {0}", Marshal.GetLastWin32Error());
                    }

                    return(true);
                }
            }

            return(false);
        }
        private void GetGroupName()
        {
            try
            {
                int i = 0;
                ArrayList GName = new ArrayList();
                Win32API api2 = new Win32API();
                CallBack myCallBack = new CallBack(api2.Report);
                Win32API.EnumWindows(myCallBack, 0);
                while (!string.IsNullOrEmpty(Win32API.GroupNames[i]))
                {
                    GName.Add(Win32API.GroupNames[i++]);
                }
                labelGroupName.Text = GName[++GNum < GName.Count ? GNum : (GNum = 0)].ToString();

                findPtr = Win32API.FindWindow("TXGuiFoundation", labelGroupName.Text);

            }
            catch
            {
                labelGroupName.Text = "未找到";
            }
        }
Beispiel #54
0
        public string GetMacAddress()
        {
            string addr = "";

            try
            {
                int       cb;
                ASTAT     adapter;
                NCB       Ncb = new NCB();
                char      uRetCode;
                LANA_ENUM lenum;

                Ncb.ncb_command = (byte)NCBCONST.NCBENUM;
                cb             = Marshal.SizeOf(typeof(LANA_ENUM));
                Ncb.ncb_buffer = Marshal.AllocHGlobal(cb);
                Ncb.ncb_length = (ushort)cb;
                uRetCode       = Win32API.Netbios(ref Ncb);
                lenum          = (LANA_ENUM)Marshal.PtrToStructure(Ncb.ncb_buffer, typeof(LANA_ENUM));
                Marshal.FreeHGlobal(Ncb.ncb_buffer);
                if (uRetCode != (short)NCBCONST.NRC_GOODRET)
                {
                    return("");
                }

                for (int i = 0; i < lenum.length; i++)
                {
                    Ncb.ncb_command  = (byte)NCBCONST.NCBRESET;
                    Ncb.ncb_lana_num = lenum.lana[i];
                    uRetCode         = Win32API.Netbios(ref Ncb);
                    if (uRetCode != (short)NCBCONST.NRC_GOODRET)
                    {
                        return("");
                    }

                    Ncb.ncb_command     = (byte)NCBCONST.NCBASTAT;
                    Ncb.ncb_lana_num    = lenum.lana[i];
                    Ncb.ncb_callname[0] = (byte)'*';
                    cb             = Marshal.SizeOf(typeof(ADAPTER_STATUS)) + Marshal.SizeOf(typeof(NAME_BUFFER)) * (int)NCBCONST.NUM_NAMEBUF;
                    Ncb.ncb_buffer = Marshal.AllocHGlobal(cb);
                    Ncb.ncb_length = (ushort)cb;
                    uRetCode       = Win32API.Netbios(ref Ncb);
                    adapter.adapt  = (ADAPTER_STATUS)Marshal.PtrToStructure(Ncb.ncb_buffer, typeof(ADAPTER_STATUS));
                    Marshal.FreeHGlobal(Ncb.ncb_buffer);

                    if (uRetCode == (short)NCBCONST.NRC_GOODRET)
                    {
                        if (i > 0)
                        {
                            addr += ":";
                        }
                        addr = string.Format("{0,2:X}{1,2:X}{2,2:X}{3,2:X}{4,2:X}{5,2:X}",
                                             adapter.adapt.adapter_address[0],
                                             adapter.adapt.adapter_address[1],
                                             adapter.adapt.adapter_address[2],
                                             adapter.adapt.adapter_address[3],
                                             adapter.adapt.adapter_address[4],
                                             adapter.adapt.adapter_address[5]);
                    }
                }
            }
            catch
            { }
            return(addr.Replace(' ', '0'));
        }
Beispiel #55
0
 /// <summary>
 /// Makes sure rc is MidiWin32Wrapper.MMSYSERR_NOERROR.  If not, throws an exception with an
 /// appropriate error message.
 /// </summary>
 /// <param name="rc"></param>
 private static void CheckReturnCode(Win32API.MMRESULT rc)
 {
     if (rc != Win32API.MMRESULT.MMSYSERR_NOERROR)
     {
         StringBuilder errorMsg = new StringBuilder(128);
         rc = Win32API.midiInGetErrorText(rc, errorMsg);
         if (rc != Win32API.MMRESULT.MMSYSERR_NOERROR)
         {
             throw new DeviceException("no error details");
         }
         throw new DeviceException(errorMsg.ToString());
     }
 }
        private void ParentWindow()
        {
            LogWriter.Log("ParentWindow", TraceEventType.Verbose);
            if (win.Handle == IntPtr.Zero)
            {
                LogWriter.Log("\tWindow handle is 0: quitting", TraceEventType.Error);
                return;
            }
            Dispatcher.Invoke(() =>
            {
                try
                {
                    hookupWinMsgDetection();

                    List <LookupRequestItem> lri = new List <LookupRequestItem>();
                    lri.Add(new LookupRequestItem("Title", Win32API.GetWindowText(win.Handle)));
                    ((DynamicsCustomerRecord)localSession.Customer.DesktopCustomer).MergeReplacementParameter(this.ApplicationName, lri, true);

                    Window _RootWindow          = System.Windows.Application.Current.MainWindow;
                    WindowInteropHelper wrapper = new WindowInteropHelper(_RootWindow);
                    HandleRef shellWindow       = new System.Runtime.InteropServices.HandleRef(wrapper, wrapper.Handle);

                    if (removeFrameAndCaption)
                    {
                        RemoveFrameAndCaption(win);
                    }
                    if (removeFromTaskbar)
                    {
                        RemoveFromTaskbar(win);
                    }
                    if (removeSizingControls)
                    {
                        RemoveSizingControls(win);
                    }
                    if (removeSizingMenu)
                    {
                        RemoveSizingMenu(win);
                    }
                    if (removeSystemMenu)
                    {
                        RemoveSystemMenu(win);
                    }
                    RestoreIfMinimized(win);

                    if (hostingMode == WindowHostingMode.SETPARENT)
                    {
                        LogWriter.Log("\tSetting Window Position Width:" + this.ActualWidth.ToString() + " Height:" + this.ActualHeight.ToString(), TraceEventType.Verbose);
                        Win32API.SetWindowPos(win.Handle, IntPtr.Zero, 0, 0, (int)this.ActualWidth, (int)this.ActualHeight, (int)0x0040);

                        LogWriter.Log("\tReparenting", TraceEventType.Verbose);
                        // parenting the window makes the automation interface
                        //_WindowParenter = new WindowParenter(new HandleRef(this, myhost.Handle), win, true, false);
                        // JAYME: I chose to use the below because knowledge of the return value of SetParent is useful
                        //        but it gets hidden in WindowParenter
                        IntPtr prevParent = SetParent(win.Handle, myhost.Handle);
                        if (prevParent != IntPtr.Zero)
                        {
                            LogWriter.Log("\tReparenting complete. " + prevParent.ToString(), TraceEventType.Verbose);
                            // CLEAR WS_POPUP and SET WS_CHILD
                            // WS_POPUP     0x80000000L
                            // WS_CHILD     0x40000000L
                            uint dwNewLong = NativeMethods.GetWindowLong(win.Handle, NativeMethods.WinUserConstant.GWL_STYLE);
                            oldWindowStyle = dwNewLong;
                            dwNewLong     ^= 0x80000000;
                            dwNewLong     |= 0x40000000;
                            NativeMethods.SetWindowLong(win.Handle, NativeMethods.WinUserConstant.GWL_STYLE, dwNewLong);
                            LogWriter.Log("\tAdjusted WS_POPUP and WS_CHILD.", TraceEventType.Verbose);
                        }
                        else
                        {
                            LogWriter.Log("\tReparenting complete. NULL", TraceEventType.Verbose);
                            int errorResult = Marshal.GetLastWin32Error();
                            LogWriter.Log("\tReparenting error. " + errorResult.ToString(), TraceEventType.Verbose);
                        }
                    }
                    else if (hostingMode == WindowHostingMode.DYNAMICPOSITIONING)
                    {
                        wp = new DPHandler(myhost, win, true);
                        RestoreIfMinimized(win);
                        wp.Activate();
                    }


                    if (WindowAttached != null)
                    {
                        WindowAttached(this, EventArgs.Empty);
                    }
                }
                catch (Exception ex)
                {
                    LogWriter.Log(ex);
                }
            });
        }
Beispiel #57
0
 /// <summary>
 /// Private Constructor, only called by the getter for the InstalledDevices property.
 /// </summary>
 /// <param name="deviceId">Position of this device in the list of all devices.</param>
 /// <param name="caps">Win32 Struct with device metadata</param>
 private InputDevice(UIntPtr deviceId, Win32API.MIDIINCAPS caps)
     : base(caps.szPname)
 {
     this.deviceId = deviceId;
     this.caps = caps;
     this.inputCallbackDelegate = new Win32API.MidiInProc(this.InputCallback);
     this.isOpen = false;
     this.clock = null;
 }
 private void ctrlAltDelToolStripMenuItem_Click(object sender, EventArgs e)
 {
     Win32API.keybd_event(0x11, 0, 0, 0);
     Win32API.keybd_event(18, 0, 0, 0);
     Win32API.keybd_event(0x2E, 0, 0, 0);
 }
Beispiel #59
0
 private IntPtr MyWndProc(IntPtr hwnd, uint uMsg, IntPtr wParam, IntPtr lParam)
 {
     Console.WriteLine("MyWndProc    hwnd = " + hwnd + "    uMsg = " + uMsg);
     return(Win32API.DefWindowProc(hwnd, uMsg, wParam, lParam));
 }
Beispiel #60
0
 /// <summary>
 /// Private Constructor, only called by the getter for the InstalledDevices property.
 /// </summary>
 /// <param name="deviceId">Position of this device in the list of all devices.</param>
 /// <param name="caps">Win32 Struct with device metadata</param>
 private InputDevice(UIntPtr deviceId, Win32API.MIDIINCAPS caps)
     : base(caps.szPname)
 {
     this.deviceId = deviceId;
     this.caps = caps;
     this.isOpen = false;
     this.clock = null;
 }