private GUIItem AddNewTaskItem(WinHandle window) { //window.TitleChanged += Window_TitleChanged; var g = new GUIItem(); Application.Current.Dispatcher.Invoke(() => { try { StackPanel s = new StackPanel(); ListBoxItem holder = new ListBoxItem(); holder.Focusable = false; s.Tag = window.Ptr.ToString(); holder.MouseLeftButtonUp += (object sender, MouseButtonEventArgs e) => { RefreshTasks(); window.MaximizeMinimize(); }; ContextMenu o = new ContextMenu(); var h = new MenuItem() { Header = "Close" }; h.Click += (object sender, RoutedEventArgs e) => { InteropHelper.CloseWindow((IntPtr)int.Parse(s.Tag.ToString())); }; o.Items.Add(h); s.ContextMenu = o; Label l = new Label(); l.Content = window.Title; s.Width = 60; l.Foreground = new SolidColorBrush(Colors.White); l.FontSize = 10; Image m = new Image(); var handle = window.WindowIcon.ToBitmap().GetHbitmap(); try { m.Source = Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); m.Width = 25; m.Height = 25; s.Children.Add(m); } finally { InteropHelper.DeleteObject(handle); } s.Children.Add(l); s.Height = 60; g.Destroy = () => { Application.Current.Dispatcher.Invoke(() => { Left += s.Width; ProcMenu.Width -= s.Width; ProcMenu.Items.Remove(ProcMenu.Items.OfType <ListBoxItem>().Where(x => x.Tag == s.Tag).First()); }); }; holder.Content = s; RefreshTasks(); ProcMenu.Items.Add(holder); Console.WriteLine("Added"); ProcMenu.Width += s.Width; Left -= s.Width; Width = ProcMenu.Width; } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }); return(g); }
public IVisio.Document DrawInteropEnumDocumentation() { this._client.Application.AssertApplicationAvailable(); var formdoc = new VisioAutomation.Models.Documents.Forms.FormDocument(); var helpstr = new System.Text.StringBuilder(); int chunksize = 70; var interop_enums = InteropHelper.GetEnums(); foreach (var enum_ in interop_enums) { int chunkcount = 0; var values = enum_.Values.OrderBy(i => i.Name).ToList(); foreach (var chunk in DeveloperCommands.Chunk(values, chunksize)) { helpstr.Length = 0; foreach (var val in chunk) { helpstr.AppendFormat("0x{0}\t{1}\n", val.Value.ToString("x"), val.Name); } var formpage = new VisioAutomation.Models.Documents.Forms.FormPage(); formpage.Size = new Drawing.Size(8.5, 11); formpage.PageMargin = new PageMargin(0.5, 0.5, 0.5, 0.5); formpage.Title = enum_.Name; formpage.Body = helpstr.ToString(); if (chunkcount == 0) { formpage.Name = string.Format("{0}", enum_.Name); } else { formpage.Name = string.Format("{0} ({1})", enum_.Name, chunkcount + 1); } //docbuilder.BodyParaSpacingAfter = 2.0; formpage.BodyTextSize = 8.0; formdoc.Pages.Add(formpage); var tabstops = new[] { new Text.TabStop(1.5, Text.TabStopAlignment.Left) }; //VA.Text.TextFormat.SetTabStops(docpage.VisioBodyShape, tabstops); chunkcount++; } } formdoc.Subject = "Visio Interop Enum Documenation"; formdoc.Title = "Visio Interop Enum Documenation"; formdoc.Creator = ""; formdoc.Company = ""; //hide_ui_stuff(docbuilder.VisioDocument); var application = this._client.Application.Get(); var doc = formdoc.Render(application); return(doc); }
private void Sync_Click(object sender, RoutedEventArgs e) { if (_token != null) { StopSync(); return; } Sync.Content = LocalizedStrings.Str2890; _token = new CancellationTokenSource(); Task.Factory.StartNew(() => { var securityPaths = new List <string>(); foreach (var dir in DriveCache.Instance.AllDrives .OfType <LocalMarketDataDrive>() .Select(drive => drive.Path) .Distinct()) { foreach (var letterDir in InteropHelper.GetDirectories(dir)) { if (_token.IsCancellationRequested) { break; } var name = Path.GetFileName(letterDir); if (name == null || name.Length != 1) { continue; } securityPaths.AddRange(InteropHelper.GetDirectories(letterDir)); } if (_token.IsCancellationRequested) { break; } } if (_token.IsCancellationRequested) { return; } var iterCount = securityPaths.Count + // кол-во проходов по директории для создания инструмента DriveCache.Instance.AllDrives.Count() * (((IList <Security>)EntityRegistry.Securities).Count + securityPaths.Count); // кол-во сбросов кэша дат this.GuiSync(() => Progress.Maximum = iterCount); var logSource = ConfigManager.GetService <LogManager>().Application; var securityIdGenerator = new SecurityIdGenerator(); var securities = EntityRegistry.Securities.ToDictionary(s => s.Id, s => new KeyValuePair <Security, bool>(s, true), StringComparer.InvariantCultureIgnoreCase); foreach (var securityPath in securityPaths) { if (_token.IsCancellationRequested) { break; } var securityId = Path.GetFileName(securityPath).FolderNameToSecurityId(); var isNew = false; var security = securities.TryGetValue(securityId).Key; if (security == null) { var firstDataFile = Directory.EnumerateDirectories(securityPath) .SelectMany(d => Directory.EnumerateFiles(d, "*.bin") .Concat(Directory.EnumerateFiles(d, "*.csv")) .OrderBy(f => Path.GetExtension(f).CompareIgnoreCase(".bin") ? 0 : 1)) .FirstOrDefault(); if (firstDataFile != null) { var id = securityIdGenerator.Split(securityId); decimal priceStep; if (Path.GetExtension(firstDataFile).CompareIgnoreCase(".bin")) { try { priceStep = File.ReadAllBytes(firstDataFile).Range(6, 16).To <decimal>(); } catch (Exception ex) { throw new InvalidOperationException(LocalizedStrings.Str2929Params.Put(firstDataFile), ex); } } else { priceStep = 0.01m; } security = new Security { Id = securityId, PriceStep = priceStep, Name = id.SecurityCode, Code = id.SecurityCode, Board = ExchangeBoard.GetOrCreateBoard(id.BoardCode), ExtensionInfo = new Dictionary <object, object>() }; securities.Add(securityId, new KeyValuePair <Security, bool>(security, false)); isNew = true; } } this.GuiSync(() => { Progress.Value++; if (isNew) { Logs.Messages.Add(new LogMessage(logSource, TimeHelper.NowWithOffset, LogLevels.Info, LocalizedStrings.Str2930Params.Put(security))); } }); } EntityRegistry.Securities.AddRange(securities.Values.Where(p => !p.Value).Select(p => p.Key)); if (_token.IsCancellationRequested) { return; } //var dataTypes = new[] //{ // Tuple.Create(typeof(ExecutionMessage), (object)ExecutionTypes.Tick), // Tuple.Create(typeof(ExecutionMessage), (object)ExecutionTypes.OrderLog), // Tuple.Create(typeof(ExecutionMessage), (object)ExecutionTypes.Order), // Tuple.Create(typeof(ExecutionMessage), (object)ExecutionTypes.Trade), // Tuple.Create(typeof(QuoteChangeMessage), (object)null), // Tuple.Create(typeof(Level1ChangeMessage), (object)null), // Tuple.Create(typeof(NewsMessage), (object)null) //}; var formats = Enumerator.GetValues <StorageFormats>().ToArray(); foreach (var drive in DriveCache.Instance.AllDrives) { foreach (var secId in drive.AvailableSecurities) { foreach (var format in formats) { foreach (var dataType in drive.GetAvailableDataTypes(secId, format)) { if (_token.IsCancellationRequested) { break; } drive .GetStorageDrive(secId, dataType.Item1, dataType.Item2, format) .ClearDatesCache(); } } if (_token.IsCancellationRequested) { break; } this.GuiSync(() => { Progress.Value++; Logs.Messages.Add(new LogMessage(logSource, TimeHelper.NowWithOffset, LogLevels.Info, LocalizedStrings.Str2931Params.Put(secId, drive.Path))); }); } if (_token.IsCancellationRequested) { break; } } }, _token.Token) .ContinueWithExceptionHandling(this, res => { Sync.Content = LocalizedStrings.Str2932; Sync.IsEnabled = true; Progress.Value = 0; _token = null; }); }
public static AllJoynBusObject CreateFromWin32Handle(IntPtr hWnd) { IWindowsDevicesAllJoynBusObjectFactoryInterop allJoynBusObjectInterop = (IWindowsDevicesAllJoynBusObjectFactoryInterop)InteropHelper.GetActivationFactory <IWindowsDevicesAllJoynBusObjectFactoryInterop>(typeof(AllJoynBusObject)); //Guid guid = typeof(AllJoynBusObject).GetInterface("IAllJoynBusObject").GUID; Guid guid = typeof(AllJoynBusObject).GUID; return(allJoynBusObjectInterop.CreateFromWin32Handle(hWnd, ref guid)); }
public LocalMarketDataStorageDrive(LocalMarketDataDrive parent, SecurityId securityId, string fileName, StorageFormats format, IMarketDataDrive drive) { if (parent == null) { throw new ArgumentNullException("parent"); } if (securityId.IsDefault()) { throw new ArgumentNullException("securityId"); } if (drive == null) { throw new ArgumentNullException("drive"); } if (fileName.IsEmpty()) { throw new ArgumentNullException("fileName"); } _parent = parent; _securityId = securityId; _fileName = fileName; _format = format; _drive = drive; _fileNameWithExtension = _fileName + GetExtension(_format); _datesDict = new Lazy <CachedSynchronizedOrderedDictionary <DateTime, DateTime> >(() => { var retVal = new CachedSynchronizedOrderedDictionary <DateTime, DateTime>(); var datesPath = GetDatesCachePath(); if (File.Exists(datesPath)) { foreach (var date in LoadDates()) { retVal.Add(date, date); } } else { var rootDir = Path; var dates = InteropHelper .GetDirectories(rootDir) .Where(dir => File.Exists(IOPath.Combine(dir, _fileNameWithExtension))) .Select(dir => IOPath.GetFileName(dir).ToDateTime(_dateFormat)); foreach (var date in dates) { retVal.Add(date, date); } SaveDates(retVal.CachedValues); } return(retVal); }).Track(); }
/// <summary> /// Initializes a new instance of the MainWindow class. /// </summary> /// public MainWindow() { string ffmpegPath = string.Format(@"../../../FFmpeg.AutoGen/FFmpeg/bin/windows/{0}", Environment.Is64BitProcess ? "x64" : "x86"); InteropHelper.RegisterLibrariesSearchPath(ffmpegPath); //InteropHelper.RegisterLibrariesSearchPath(opencvPath); this.guide = new Guide(); // one sensor is currently supported this.kinectSensor = KinectSensor.GetDefault(); // get the coordinate mapper this.coordinateMapper = this.kinectSensor.CoordinateMapper; // get the depth (display) extents FrameDescription frameDescription = this.kinectSensor.DepthFrameSource.FrameDescription; // get size of joint space this.displayWidth = frameDescription.Width; this.displayHeight = frameDescription.Height; // open the reader for the body frames this.bodyFrameReader = this.kinectSensor.BodyFrameSource.OpenReader(); // a bone defined as a line between two joints this.bones = new List <Tuple <JointType, JointType> >(); // Torso this.bones.Add(new Tuple <JointType, JointType>(JointType.Head, JointType.Neck)); this.bones.Add(new Tuple <JointType, JointType>(JointType.Neck, JointType.SpineShoulder)); this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineShoulder, JointType.SpineMid)); this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineMid, JointType.SpineBase)); this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineShoulder, JointType.ShoulderRight)); this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineShoulder, JointType.ShoulderLeft)); this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineBase, JointType.HipRight)); this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineBase, JointType.HipLeft)); // Right Arm this.bones.Add(new Tuple <JointType, JointType>(JointType.ShoulderRight, JointType.ElbowRight)); this.bones.Add(new Tuple <JointType, JointType>(JointType.ElbowRight, JointType.WristRight)); this.bones.Add(new Tuple <JointType, JointType>(JointType.WristRight, JointType.HandRight)); this.bones.Add(new Tuple <JointType, JointType>(JointType.HandRight, JointType.HandTipRight)); this.bones.Add(new Tuple <JointType, JointType>(JointType.WristRight, JointType.ThumbRight)); // Left Arm this.bones.Add(new Tuple <JointType, JointType>(JointType.ShoulderLeft, JointType.ElbowLeft)); this.bones.Add(new Tuple <JointType, JointType>(JointType.ElbowLeft, JointType.WristLeft)); this.bones.Add(new Tuple <JointType, JointType>(JointType.WristLeft, JointType.HandLeft)); this.bones.Add(new Tuple <JointType, JointType>(JointType.HandLeft, JointType.HandTipLeft)); this.bones.Add(new Tuple <JointType, JointType>(JointType.WristLeft, JointType.ThumbLeft)); // Right Leg this.bones.Add(new Tuple <JointType, JointType>(JointType.HipRight, JointType.KneeRight)); this.bones.Add(new Tuple <JointType, JointType>(JointType.KneeRight, JointType.AnkleRight)); this.bones.Add(new Tuple <JointType, JointType>(JointType.AnkleRight, JointType.FootRight)); // Left Leg this.bones.Add(new Tuple <JointType, JointType>(JointType.HipLeft, JointType.KneeLeft)); this.bones.Add(new Tuple <JointType, JointType>(JointType.KneeLeft, JointType.AnkleLeft)); this.bones.Add(new Tuple <JointType, JointType>(JointType.AnkleLeft, JointType.FootLeft)); // populate body colors, one for each BodyIndex this.bodyColors = new List <System.Windows.Media.Pen>(); this.bodyColors.Add(new System.Windows.Media.Pen(System.Windows.Media.Brushes.Red, 6)); this.bodyColors.Add(new System.Windows.Media.Pen(System.Windows.Media.Brushes.Orange, 6)); this.bodyColors.Add(new System.Windows.Media.Pen(System.Windows.Media.Brushes.Green, 6)); this.bodyColors.Add(new System.Windows.Media.Pen(System.Windows.Media.Brushes.Blue, 6)); this.bodyColors.Add(new System.Windows.Media.Pen(System.Windows.Media.Brushes.Indigo, 6)); this.bodyColors.Add(new System.Windows.Media.Pen(System.Windows.Media.Brushes.Violet, 6)); // set IsAvailableChanged event notifier this.kinectSensor.IsAvailableChanged += this.Sensor_IsAvailableChanged; // open the sensor this.kinectSensor.Open(); // set the status text this.StatusText = this.kinectSensor.IsAvailable ? Properties.Resources.RunningStatusText : Properties.Resources.NoSensorStatusText; // Create the drawing group we'll use for drawing this.drawingGroup = new DrawingGroup(); // Create an image source that we can use in our image control this.kinectImageSource = new DrawingImage(this.drawingGroup); this.droneImage = new System.Windows.Controls.Image(); // use the window object as the view model in this simple example this.DataContext = this; this.droneController = new DroneController(); droneController.VideoFrameArrived += droneController_VideoFrameArrived; droneController.BatteryChanged += droneController_BatteryChanged; droneController.AltitudeChanged += droneController_AltitudeChanged; // initialize the components (controls) of the window this.InitializeComponent(); this.initAnimationComponent(); }
public IEnumerable <ServiceStatus> GetServiceDisplayNames(BitnamiRedmineStack stack, ServiceConfiguration configuration) { var statusList = new List <ServiceStatus>(); try { var services = new[] { new { Path = Path.Combine(stack.InstallLocation, ApachePath), Condition = configuration.Apache }, new { Path = Path.Combine(stack.InstallLocation, MySqlPath), Condition = configuration.MySql }, new { Path = Path.Combine(stack.InstallLocation, RedminePath), Condition = configuration.Redmine }, new { Path = Path.Combine(stack.InstallLocation, SubversionPath), Condition = configuration.Subversion } }; const string registryKey = @"SYSTEM\CurrentControlSet\services"; using (var key = Registry.LocalMachine.OpenSubKey(registryKey)) { if (key == null) { throw new KeyNotFoundException($"サブキー 'HKEY_LOCAL_MACHINE\\{registryKey}' が存在しません。"); } var subKeyNames = key.GetSubKeyNames(); foreach (var subkeyName in subKeyNames) { using (var subkey = key.OpenSubKey(subkeyName)) { var imagePath = subkey?.GetValue("ImagePath") as string; if (string.IsNullOrWhiteSpace(imagePath)) { continue; } var displayName = subkey.GetValue("DisplayName") as string; if (string.IsNullOrWhiteSpace(displayName)) { continue; } // 時々、8.3 形式の短いパスがある // さらに、引数を含むパスがいるため、分解してから長い形式のパスに変換する // が、長い形式のパスを System.IO.Path.GetFullPath で // 変関すると例外を投げるので、Win32 API の GetLongPathName を使う try { var splitArgs = InteropHelper.SplitArgs(imagePath); if (splitArgs == null || splitArgs.Length == 0) { continue; } imagePath = InteropHelper.GetLongPathName(splitArgs[0]); } catch { } if (imagePath == null) { continue; } foreach (var service in services) { if (!service.Condition) { continue; } if (imagePath.Contains(service.Path)) { var startupType = GetStartupType(subkey); var status = new ServiceStatus(this, subkeyName, startupType); statusList.Add(status); } } } } } } catch (Exception e) { this._LogService.Error(e.Message); throw; } return(statusList); }
private void Logout(object sender, RoutedEventArgs e) { InteropHelper.ExitWindowsEx(0, 0); }
private MetisStatus Partition(int nparts, int[] epart, int[] npart, MetisOptions options, bool dual) { if (ne <= 0) { return(MetisStatus.ERROR_INPUT); } if (epart == null || epart.Length < ne) { return(MetisStatus.ERROR_INPUT); } if (npart == null || npart.Length < nn) { return(MetisStatus.ERROR_INPUT); } int objval = 0; int ncommon = 2; // for triangles float[] tpwgts = GetWeights(nparts, ncon); var handles = new List <GCHandle>(); // Pin array data and get pointers. var p_eptr = InteropHelper.Pin(eptr, handles); var p_eind = InteropHelper.Pin(eind, handles); var p_ewgt = InteropHelper.Pin(ewgt, handles); var p_tpwgts = InteropHelper.Pin(tpwgts, handles); var p_epart = InteropHelper.Pin(epart, handles); var p_npart = InteropHelper.Pin(npart, handles); var p_opts = options == null ? IntPtr.Zero : InteropHelper.Pin(options.raw, handles); int l_ne = ne; int l_nn = nn; int status = 0; try { if (dual) { status = NativeMethods.PartMeshDual(ref l_ne, ref l_nn, p_eptr, p_eind, p_ewgt, IntPtr.Zero, ref ncommon, ref nparts, p_tpwgts, p_opts, ref objval, p_epart, p_npart); } else { status = NativeMethods.PartMeshNodal(ref l_ne, ref l_nn, p_eptr, p_eind, IntPtr.Zero, IntPtr.Zero, ref nparts, p_tpwgts, p_opts, ref objval, p_epart, p_npart); } } catch (Exception) { throw; } finally { InteropHelper.Free(handles); } return((MetisStatus)status); }
private MetisGraph ToGraph(bool dual, int ncommon) { int numflag = 0; IntPtr p_xadj; IntPtr p_adjncy; var handles = new List <GCHandle>(); // Pin array data. var p_eptr = InteropHelper.Pin(eptr, handles); var p_eind = InteropHelper.Pin(eind, handles); int status = 0; int l_ne = ne; int l_nn = nn; MetisGraph graph = null; try { if (dual) { status = NativeMethods.MeshToDual(ref l_ne, ref l_nn, p_eptr, p_eind, ref ncommon, ref numflag, out p_xadj, out p_adjncy); } else { status = NativeMethods.MeshToNodal(ref l_ne, ref l_nn, p_eptr, p_eind, ref numflag, out p_xadj, out p_adjncy); } if (status > 0) { // Number of vertices int nv = dual ? this.ne : this.nn; var xadj = new int[nv + 1]; Marshal.Copy(p_xadj, xadj, 0, nv + 1); // Number of edges int ne = xadj[nv]; var adjncy = new int[ne]; Marshal.Copy(p_adjncy, adjncy, 0, ne); graph = new MetisGraph(nv, ne / 2, xadj, adjncy); // Free native memory. NativeMethods.Free(p_xadj); NativeMethods.Free(p_adjncy); } } catch (Exception) { throw; } finally { InteropHelper.Free(handles); } return(graph); }
public Form1() { InitializeComponent(); MessageBox.Show($"IsAppContainer: {InteropHelper.IsAppContainer()}; HasPackageIdentity: {InteropHelper.HasPackageIdentity()}"); }
public EnumType GetInteropEnum(string name) { return(InteropHelper.GetEnum(name)); }
public List <EnumType> GetInteropEnums() { return(InteropHelper.GetEnums()); }
/// <summary> /// Method. /// </summary> /// <param name=""></param> /// <returns>Updates/Refreshes the Window</returns> public void Update() { InteropHelper.Do(string.Format("Update Window {0}", _windowID)); }
/// <summary> /// 指定ウィンドウハンドルの範囲をキャプチャします。 /// </summary> /// <param name="handle">ウィンドウハンドル</param> /// <returns>ビットマップ</returns> public static Bitmap CaptureScreen(IntPtr handle) { return(CaptureScreen(InteropHelper.GetWindowSize(handle, false))); }
/// <summary> /// Constructor. /// </summary> /// <param name="windowID">ID of the Window</param> /// <returns></returns> public Window(int windowID) { _windowID = windowID; _windowTitle = InteropHelper.GetWindowName(_windowID); _windowType = InteropHelper.GetWindowType(_windowID); }
public override void RemoveChild(TreeViewItemViewModel child) { if (ScoutType.Mode == (int)Mode.Formation) { FormationViewModel formationVM = child as FormationViewModel; if (formationVM != null) { InteropHelper.DeleteToRecycleBin(formationVM.FormationPath, false); //File.Delete(formationVM.FormationPath); if (File.Exists(formationVM.FormationPath + ".FD")) { InteropHelper.DeleteToRecycleBin(formationVM.FormationPath + ".FD", false); } if (File.Exists(formationVM.FormationPath + ".BMP")) { InteropHelper.DeleteToRecycleBin(formationVM.FormationPath + ".BMP", false); } // 09-19-2010 Scott if (Directory.Exists(formationVM.PlayFolderPath)) { InteropHelper.DeleteToRecycleBin(formationVM.PlayFolderPath, false); } } FolderViewModel folderVM = child as FolderViewModel; if (folderVM != null && Directory.Exists(folderVM.FolderPath)) { InteropHelper.DeleteToRecycleBin(folderVM.FolderPath, false); //Directory.Delete(folderVM.FolderPath, true); } TitleViewModel tvm = child as TitleViewModel; if (tvm != null && File.Exists(tvm.TitlePath)) { InteropHelper.DeleteToRecycleBin(tvm.TitlePath, false); if (File.Exists(tvm.TitlePath + ".FD")) { InteropHelper.DeleteToRecycleBin(tvm.TitlePath + ".FD", false); } } //PersonnelViewModel pvm = child as PersonnelViewModel; //if (pvm != null) //{ // Directory.Delete(pvm.PersonnelPath,true); //} } // 08-30-2010 Scott if (ScoutType.Mode == (int)Mode.Adjustment) { } base.RemoveChild(child); }
private void Lock(object sender, RoutedEventArgs e) { InteropHelper.LockWorkStation(); }
/// <summary> /// Method. /// </summary> /// <param name=""></param> /// <returns>Resets the Title of the Window to the default (dynamic) value</returns> public void ResetName() { InteropHelper.Do(string.Format("Set Window {0} Title Default", _windowID)); _windowTitle = InteropHelper.GetWindowName(_windowID); }
private void SettingsDialog_Load(object sender, EventArgs e) { CultureInfo culture; DockItem item; Image icon; fish.UseDenomination = true; fish.Settings.MaxScale = 1.5; fish.Settings.ScaleCaption = false; fish.ItemsLayout = ItemsLayout.Default; fish.Settings.LeftMargin = 12; fish.Settings.IconsSpacing = 34; fish.DockOrientation = DockOrientation.Vertical; icon = NativeThemeManager.Load("SmallKrento.png"); item = fish.AddItem(SR.General, icon); item.Tag = 1; icon.Dispose(); icon = NativeThemeManager.Load("exec.png"); item = fish.AddItem(SR.Tuning, icon); item.Tag = 2; icon.Dispose(); icon = BitmapPainter.ResizeBitmap(KrentoRing.DefaultRingImage, 48, 48, false); item = fish.AddItem(SR.Circle, icon); item.Tag = 3; icon.Dispose(); activeWorkplace = workplaceGeneral; workplaceGeneral.Visible = true; workplaceManager.Visible = false; workplaceTuning.Visible = false; workplaceGeneral.BringToFront(); #if PORTABLE edtRunWindows.Enabled = false; btnCircle.Enabled = false; #else edtRunWindows.Checked = InteropHelper.GetStartup("Krento"); #endif if ((GlobalSettings.Modifiers == Keys.LWin) && (GlobalSettings.Shortcut == Keys.S)) { edtUseDefault.Checked = true; edtHotKey.Enabled = false; } else { edtUseDefault.Checked = false; edtHotKey.Enabled = true; this.modifierHotKeys = GlobalSettings.Modifiers; this.shortcut = GlobalSettings.Shortcut; } switch (GlobalSettings.MouseHook) { case MouseHookButton.Wheel: rbWheel.Checked = true; break; case MouseHookButton.XButton1: rbXButton1.Checked = true; break; case MouseHookButton.XButton2: rbXButton2.Checked = true; break; } edtShiftButton.Checked = ((GlobalSettings.MouseModifiers & Keys.Shift) != 0); edtAltButton.Checked = ((GlobalSettings.MouseModifiers & Keys.Alt) != 0); edtControlButton.Checked = ((GlobalSettings.MouseModifiers & Keys.Control) != 0); edtShowHintWindow.Checked = GlobalSettings.ShowStoneHint; edtShowAlerts.Checked = GlobalSettings.ShowPopupAlerts; edtTrayIcon.Checked = GlobalSettings.ShowTrayIcon; edtShowSplashScreen.Checked = GlobalSettings.ShowSplashScreen; edtManagerButtons.Checked = GlobalSettings.ShowManagerButtons; edtUseSounds.Checked = GlobalSettings.UseSound; edtHideOnClick.Checked = GlobalSettings.HideOnClick; edtRotateOnClick.Checked = GlobalSettings.RotateOnClick; edtCheckUpdates.Checked = GlobalSettings.CheckUpdate; edtLiveReflection.Checked = GlobalSettings.LiveReflection; edtDesktopClick.Checked = GlobalSettings.DesktopClick; edtRightClick.Checked = GlobalSettings.UseRightClick; edtCircleSelector.Checked = GlobalSettings.CircleSelector; edtUseMouse.Checked = GlobalSettings.UseMouseActivation; edtKeyboardActivation.Checked = GlobalSettings.UseKeyboardActivation; edtStonesNumber.Value = GlobalSettings.DefaultStonesNumber; goodNumber = Math.Min(GlobalSettings.FadeDelay, (int)edtFadeDelay.Maximum); edtFadeDelay.Value = Math.Max(goodNumber, edtFadeDelay.Minimum); goodNumber = Math.Min(GlobalSettings.Radius, (int)edtRadius.Maximum); edtRadius.Value = Math.Max(goodNumber, edtRadius.Minimum); goodNumber = Math.Min(GlobalSettings.WindowHeight, (int)edtWindowHeight.Maximum); edtWindowHeight.Value = Math.Max(goodNumber, edtWindowHeight.Minimum); goodNumber = Math.Min(GlobalSettings.WindowWidth, (int)edtWindowWidth.Maximum); edtWindowWidth.Value = Math.Max(goodNumber, edtWindowWidth.Minimum); goodNumber = Math.Min(GlobalSettings.Transparency, (int)edtTransparency.Maximum); edtTransparency.Value = Math.Max(goodNumber, edtTransparency.Minimum); goodNumber = Math.Min(GlobalSettings.StoneSize, (int)edtStoneSize.Maximum); edtStoneSize.Value = Math.Max(goodNumber, edtStoneSize.Minimum); goodNumber = Math.Min(GlobalSettings.IconSize, (int)edtIconSize.Maximum); edtIconSize.Value = Math.Max(goodNumber, edtIconSize.Minimum); switch (KrentoContext.MainForm.Manager.CircleLocation) { case CircleLocation.Point: rbMousePosition.Checked = true; break; case CircleLocation.ScreenCenter: rbScreenCenter.Checked = true; break; case CircleLocation.Fixed: rbFixed.Checked = true; break; default: break; } if (NativeMethods.IsWow64()) { edtDesktopClick.Enabled = false; } cbLanguage.ValueMember = "NativeName"; //"EnglishName" cbLanguage.Items.Add(new CultureInfo("en-US")); languageIndex = 0; string[] langFiles = Directory.GetFiles(GlobalConfig.LanguagesFolder, "*.lng"); foreach (string lang in langFiles) { string langName = Path.GetFileNameWithoutExtension(lang); if (!TextHelper.SameText(langName, "en-US")) { try { culture = new CultureInfo(langName); } catch { culture = null; } if (culture != null) { idx = cbLanguage.Items.Add(culture); if (TextHelper.SameText(langName, GlobalSettings.Language)) { languageIndex = idx; } } } } cbLanguage.SelectedIndex = languageIndex; KrentoSkinInfo defaultSkin = new KrentoSkinInfo(null, SR.DefaultSkin); cbMenuSkins.Items.Add(defaultSkin); menuSkinIndex = 0; string GlobalMenuSkinFile = ""; if (!string.IsNullOrEmpty(GlobalSettings.MenuSkin)) { GlobalMenuSkinFile = FileOperations.StripFileName(GlobalSettings.MenuSkin); } string[] skinFiles = Directory.GetFiles(GlobalConfig.MenusFolder, "*.ini", SearchOption.AllDirectories); foreach (string skinFile in skinFiles) { KrentoSkinInfo skin = new KrentoSkinInfo(skinFile, KrentoMenuSkin.GetSkinCaption(skinFile)); idx = cbMenuSkins.Items.Add(skin); if (TextHelper.SameText(skin.FileName, GlobalMenuSkinFile)) { menuSkinIndex = idx; } } cbMenuSkins.ValueMember = "Caption"; cbMenuSkins.SelectedIndex = menuSkinIndex; menuSkinFile = GlobalSettings.MenuSkin; this.Text = SR.Settings; btnCancel.Text = SR.Cancel; this.hintInfo.SetToolTip(this.btnCancel, SR.FileConfigCancelHint); btnOK.Text = SR.OK; gbRunWindows.Text = SR.KrentoStartup; edtRunWindows.Text = SR.RunWithWindows; gbKeyboard.Text = SR.KeyboardActivation; edtUseDefault.Text = SR.UseDefaultKey; gbMouseActivation.Text = SR.MouseActivation; hintInfo.SetToolTip(gbMouseActivation, SR.MouseActivation); edtControlButton.Text = SR.ButtonControl; this.hintInfo.SetToolTip(this.edtControlButton, SR.ButtonControl); edtShiftButton.Text = SR.ButtonShift; this.hintInfo.SetToolTip(this.edtShiftButton, SR.ButtonShift); edtAltButton.Text = SR.ButtonAlt; this.hintInfo.SetToolTip(this.edtAltButton, SR.ButtonAlt); gbRingLocation.Text = SR.RingLocation; rbScreenCenter.Text = SR.ScreenCenter; rbMousePosition.Text = SR.MouseCursorPosition; btnCircle.Text = SR.AssociateRing; lblHint.Text = SR.UseCtrlTab; rbXButton1.Text = SR.MouseActionOneButton; rbXButton2.Text = SR.MouseActionTwoButton; rbWheel.Text = SR.MouseWheelClick; gbPersonalization.Text = SR.Personalization; gbUserFolders.Text = SR.UserFolders; gbMaintainance.Text = SR.Maintainance; edtTrayIcon.Text = SR.ShowTrayIcon; edtShowSplashScreen.Text = SR.ShowSplashScreen; edtShowAlerts.Text = SR.ShowPopupAlerts; btnOpenSkins.Text = SR.OpenSkinsFolder; btnOpenStones.Text = SR.OpenStonesFolder; btnOpenData.Text = SR.OpenDataFolder; btnOpenCache.Text = SR.OpenCacheFolder; btnClearCache.Text = SR.ClearCache; gbLanguage.Text = SR.Language; lblWindowHeight.Text = SR.WindowHeight; lblWindowWidth.Text = SR.WindowWidth; lblRadius.Text = SR.Radius; lblStoneSize.Text = SR.StoneSize; lblTransparency.Text = SR.Trancparency; lblFadeDelay.Text = SR.FadeDelay; gbMenuSkins.Text = SR.MenuSkins; gbManager.Text = SR.Circle; btnReset.Text = SR.ResetToDefault; btnBackup.Text = SR.BackupData; btnSettings.Text = SR.AdvancedSettings + "..."; edtKeyboardActivation.Text = SR.ActivateUsingKeyboard; edtUseMouse.Text = SR.ActivateUsingMouse; rbFixed.Text = SR.FixedPosition; edtCircleSelector.Text = SR.ShowSelector; edtDesktopClick.Text = SR.DesktopClick; edtRightClick.Text = SR.RightButtonActivation; lblStonesNumber.Text = SR.StonesNumber; lblIconSize.Text = SR.IconSize; edtRotateOnClick.Text = SR.RotateOnClick; edtShowCircleStartup.Text = SR.ActivateOnStart; edtUseSounds.Text = SR.UseSounds; edtCheckUpdates.Text = SR.CheckUpdates; edtLiveReflection.Text = SR.LiveReflection; edtManagerButtons.Text = SR.ShowManagerButtons; edtShowHintWindow.Text = SR.ShowStonesHint; edtHideOnClick.Text = SR.HideOnClick; }
//------------------------------------------------------------ #region Methods for Min/Max/Restore/Set Front /// <summary> /// Method. /// </summary> /// <param name=""></param> /// <returns>Makes the Window the front most window</returns> public void SetFront() { InteropHelper.Do(string.Format("Set Window {0} Front", _windowID)); }
/// <summary> /// Synchronize securities with storage. /// </summary> /// <param name="drives">Storage drives.</param> /// <param name="securityStorage">Securities meta info storage.</param> /// <param name="exchangeInfoProvider">Exchanges and trading boards provider.</param> /// <param name="newSecurity">The handler through which a new instrument will be passed.</param> /// <param name="updateProgress">The handler through which a progress change will be passed.</param> /// <param name="logsReceiver">Logs receiver.</param> /// <param name="isCancelled">The handler which returns an attribute of search cancel.</param> public static void SynchronizeSecurities(this IEnumerable <IMarketDataDrive> drives, ISecurityStorage securityStorage, IExchangeInfoProvider exchangeInfoProvider, Action <Security> newSecurity, Action <int, int> updateProgress, Func <bool> isCancelled, ILogReceiver logsReceiver) { if (drives == null) { throw new ArgumentNullException(nameof(drives)); } if (securityStorage == null) { throw new ArgumentNullException(nameof(securityStorage)); } if (exchangeInfoProvider == null) { throw new ArgumentNullException(nameof(exchangeInfoProvider)); } if (newSecurity == null) { throw new ArgumentNullException(nameof(newSecurity)); } if (updateProgress == null) { throw new ArgumentNullException(nameof(updateProgress)); } if (isCancelled == null) { throw new ArgumentNullException(nameof(isCancelled)); } if (logsReceiver == null) { throw new ArgumentNullException(nameof(logsReceiver)); } var securityPaths = new List <string>(); var progress = 0; foreach (var dir in drives.Select(drive => drive.Path).Distinct()) { foreach (var letterDir in InteropHelper.GetDirectories(dir)) { if (isCancelled()) { break; } var name = Path.GetFileName(letterDir); if (name == null || name.Length != 1) { continue; } securityPaths.AddRange(InteropHelper.GetDirectories(letterDir)); } if (isCancelled()) { break; } } if (isCancelled()) { return; } // кол-во проходов по директории для создания инструмента var iterCount = securityPaths.Count; updateProgress(0, iterCount); var securities = securityStorage.LookupAll().ToDictionary(s => s.Id, s => s, StringComparer.InvariantCultureIgnoreCase); foreach (var securityPath in securityPaths) { if (isCancelled()) { break; } var securityId = Path.GetFileName(securityPath).FolderNameToSecurityId(); var isNew = false; var security = securities.TryGetValue(securityId); if (security == null) { var firstDataFile = Directory.EnumerateDirectories(securityPath) .SelectMany(d => Directory.EnumerateFiles(d, "*.bin") .Concat(Directory.EnumerateFiles(d, "*.csv")) .OrderBy(f => Path.GetExtension(f).CompareIgnoreCase(".bin") ? 0 : 1)) .FirstOrDefault(); if (firstDataFile != null) { var id = securityId.ToSecurityId(); decimal priceStep; if (Path.GetExtension(firstDataFile).CompareIgnoreCase(".bin")) { try { priceStep = File.ReadAllBytes(firstDataFile).Range(6, 16).To <decimal>(); } catch (Exception ex) { throw new InvalidOperationException(LocalizedStrings.Str2929Params.Put(firstDataFile), ex); } } else { priceStep = 0.01m; } security = new Security { Id = securityId, PriceStep = priceStep, Name = id.SecurityCode, Code = id.SecurityCode, Board = exchangeInfoProvider.GetOrCreateBoard(id.BoardCode), }; securities.Add(securityId, security); securityStorage.Save(security); newSecurity(security); isNew = true; } } updateProgress(progress++, iterCount); if (isNew) { logsReceiver.AddInfoLog(LocalizedStrings.Str2930Params, security); } } }
/// <summary> /// Method. /// </summary> /// <param name=""></param> /// <returns>Minimizes the Window</returns> public void Minimize() { InteropHelper.Eval(String.Format("Set Window {0} Min", _windowID)); }
public static AllJoynBusAttachment CreateFromWin32Handle(IntPtr hWnd, bool enableAboutData) { IWindowsDevicesAllJoynBusAttachmentFactoryInterop allJoynBusAttachmentInterop = (IWindowsDevicesAllJoynBusAttachmentFactoryInterop)InteropHelper.GetActivationFactory <IWindowsDevicesAllJoynBusAttachmentInterop>(typeof(AllJoynBusAttachment)); //Guid guid = typeof(AllJoynBusAttachmentFactory).GetInterface("IAllJoynBusAttachmentFactory").GUID; Guid guid = typeof(AllJoynBusAttachment).GUID; return(allJoynBusAttachmentInterop.CreateFromWin32Handle(hWnd, enableAboutData, ref guid)); }
/// <summary> /// Method. /// </summary> /// <param name=""></param> /// <returns>Restores the Window</returns> public void Restore() { InteropHelper.Eval(String.Format("Set Window {0} Restore", _windowID)); }
public static IntPtr GetWin32Handle() { IWindowsDevicesAllJoynBusAttachmentInterop allJoynBusAttachmentInterop = (IWindowsDevicesAllJoynBusAttachmentInterop)InteropHelper.GetActivationFactory <IWindowsDevicesAllJoynBusAttachmentInterop>(typeof(AllJoynBusAttachment)); //Guid guid = typeof(AllJoynBusAttachment).GetInterface("IAllJoynBusAttachment").GUID; //Guid guid = typeof(AllJoynBusAttachment).GUID; return(allJoynBusAttachmentInterop.GetWin32Handle()); }
//------------------------------------------------------------ #region Methods for Cloning/Updating /// <summary> /// Method. /// </summary> /// <param name=""></param> /// <returns>Closes the Window</returns> public void Clone() { InteropHelper.Do(string.Format("Run Command WindowInfo({0},15)", _windowID)); }
public MainWindow() { Task <int> taskStart = null; CancellationToken taskToken = new CancellationToken(false); try { if (CommandArgs.This.IsValidate == true) { Closing += MainWindow_Closing; this.InitializeComponent(); this.StartNewEventSession(); //Logging("Browser::ctor () - new WindowManager() - ???..."); this.windowManager = new WindowManager(); Logging(string.Format("{1}{0}Browser::ctor () - new WindowManager([DateTime={2}]) - processing.." , Environment.NewLine , string.Concat(Enumerable.Repeat("*---", 16)) , DateTime.UtcNow)); taskStart = Task.Factory.StartNew(delegate { string cookies = string.Empty; if ((CommandArgs.This.IsUrlValidate == true) && (CommandArgs.This.Url.Contains(CatalogApi.UrlConstants.ChevroletOpelGroupRoot) == true) && (!(CommandArgs.This.Mode == CommandArgs.MODE.primary))) { // режимы: proxy, slave base.Dispatcher.BeginInvoke(new Action(delegate { base.Title = "***Chevrolet-Opel Dealer Online***"; }), new object[0]); if (CommandArgs.This.Mode == CommandArgs.MODE.proxy) { // режим proxy if (RequestHelper.Client == null) { RequestHelper.Client = new ServiceReference.RequestProcessorClient(); } else { ; } InteropHelper.GetSystemTime(ref this.time); RemoteCertificateValidationCallback delegateCertificateValidationAlwaysTrust = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => { return(true); }; ServicePointManager.ServerCertificateValidationCallback += delegateCertificateValidationAlwaysTrust; Logging(string.Format("::InitializeSettings() - успех...")); RequestHelper.Client.LogConnection(string.Format(@"{0}\{1}", Environment.MachineName, "Browser") , FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion); AccountManager.Account = RequestHelper.Client.GetUnoccupiedAccount(); cookies = OpenSession(CommandArgs.This.Url, CommandArgs.This.ProviderId); } else if ((CommandArgs.This.Mode == CommandArgs.MODE.slave) && (CommandArgs.This.ContainsKey(CommandArgs.KEYS.session) == true) && (string.IsNullOrWhiteSpace(CommandArgs.This[CommandArgs.KEYS.session]) == false)) { // режим slave Logging(String.Format("Browser::ctor () - read local session settings(file={0}) - ???..." , CommandArgs.This[CommandArgs.KEYS.session])); if (File.Exists(CommandArgs.This[CommandArgs.KEYS.session]) == true) { using (FileStream fileStream = new FileStream(CommandArgs.This[CommandArgs.KEYS.session], FileMode.Open, FileAccess.Read)) { using (StreamReader streamReader = new StreamReader(fileStream)) { cookies = streamReader.ReadToEnd(); } } Logging(String.Format( "Browser::ctor () - read local session settings(file={0}) - success..." , CommandArgs.This[CommandArgs.KEYS.session])); } else { Logging(String.Format( "Browser::ctor () - read local session settings(file={0}) - not exists..." , CommandArgs.This[CommandArgs.KEYS.session])); } } else { ; } if (string.IsNullOrEmpty(cookies) == false) { Logging(String.Format("Browser::ctor (cookies={0}) - cookies not empty..." , cookies)); string urlSetCookie = string.Format("{0}/", CommandArgs.This.Url) // / , urlNavigateDoLogin = string.Format("{0}/users/login.html", CommandArgs.This.Url); // /users/login.html Logging(String.Format("Url to SetCookie (Url={0}) - ..." , urlSetCookie)); Logging(String.Format("Url to navigate do login (Url={0}) - ..." , urlNavigateDoLogin)); List <Cookie> list; try { list = JsonConvert.DeserializeObject <List <Cookie> >(cookies); Logging(String.Format("Cookies DeserializeObject ... (Length={0})", list.Count)); foreach (Cookie c in list) { Logging(String.Format("Browser::ctor () - InternetSetCookie to={0}, key={1}, value={2}..." , urlSetCookie , c.Name , c.Value)); if (MainWindow.InternetSetCookie(urlSetCookie , c.Name, c.Value) == false) { Logging(string.Format("::InternetSetCookie () - ошибка...")); } else { ; } } } catch (Exception ex) { Logging(ex); } Logging(String.Format("Browser to Navigate (Url={0}) - ..." , urlNavigateDoLogin)); base.Dispatcher.BeginInvoke(new Action(delegate { this.InternetExplorer.Navigate(urlNavigateDoLogin); }), new object[0]); return(0); } else { return(-1); } } else if ((CommandArgs.This.IsUrlValidate == true) && (new Uri(CommandArgs.This.Url).IsAbsoluteUri == true)) { // режим primary base.Dispatcher.BeginInvoke(new Action(delegate { this.InternetExplorer.Navigate(CommandArgs.This.Url); }), new object[0]); return(1); } else { System.Windows.MessageBox.Show(string.Format("Error opening catalog. Please report to administrator.{0}" + "Кол-во аргументов: {1}{0}" + "обязательный аргумент {2}={3}{0}" + "обязательный аргумент {4}={5}{0}" + "необязательный аргумент {6}={7}{0}" , Environment.NewLine , CommandArgs.This.Count , CommandArgs.KEYS.mode, CommandArgs.This[CommandArgs.KEYS.mode] , CommandArgs.KEYS.url, CommandArgs.This[CommandArgs.KEYS.url] , CommandArgs.KEYS.session, CommandArgs.This.ContainsKey(CommandArgs.KEYS.session) == true ? CommandArgs.This[CommandArgs.KEYS.session] : "отсутствует")); return(-1); } }, taskToken); taskStart.Wait(taskToken); if (taskStart.Result < 0) { base.Close(); } else { ; } } else { System.Windows.MessageBox.Show(string.Format("Error opening catalog. Please report to administrator.{0}" + "Кол-во аргументов: {1}{0}" + "обязательный аргумент {2}={3}{0}" + "обязательный аргумент {4}={5}{0}" + "необязательный аргумент {6}={7}{0}" , Environment.NewLine , CommandArgs.This.Count , CommandArgs.KEYS.mode, CommandArgs.This.ContainsKey(CommandArgs.KEYS.mode) == true ? CommandArgs.This[CommandArgs.KEYS.mode] : "отсутствует" , CommandArgs.KEYS.url, CommandArgs.This.ContainsKey(CommandArgs.KEYS.url) == true ? CommandArgs.This[CommandArgs.KEYS.url] : "отсутствует" , CommandArgs.KEYS.session, CommandArgs.This.ContainsKey(CommandArgs.KEYS.session) == true ? CommandArgs.This[CommandArgs.KEYS.session] : "отсутствует")); base.Close(); } } catch (System.Threading.Tasks.TaskCanceledException ex) { Logging(ex, true); } catch (Exception ex) { Logging(ex, true); } if (taskStart?.Status == TaskStatus.Faulted) { Close(); } else { ; } }
public static void ShowPlayToUIForWindow(IntPtr hWnd) { IPlayToManagerInterop playToManagerInterop = (IPlayToManagerInterop)InteropHelper.GetActivationFactory <IPlayToManagerInterop>(typeof(PlayToManager)); playToManagerInterop.ShowPlayToUIForWindow(hWnd); }