Esempio n. 1
0
        private static void Main()
        {
            bool exists = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)).Length > 1;

            if (exists)
            {
                MessageBox.Show("Программа уже запущена!", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            AppDomain.CurrentDomain.AssemblyResolve += (o, ev) =>
            {
                string folderPath   = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string assemblyPath = Path.Combine(folderPath, "lib", new AssemblyName(ev.Name).Name);
                if (File.Exists(assemblyPath + ".dll"))
                {
                    return(Assembly.LoadFrom(assemblyPath + ".dll"));
                }
                if (File.Exists(assemblyPath + ".exe"))
                {
                    return(Assembly.LoadFrom(assemblyPath + ".exe"));
                }
                return(null);
            };

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Program    program = new Program();
            MainWindow window  = new MainWindow(program);

            window.FormClosing += program.onFormMainClosing;
            Application.Run(window);
        }
Esempio n. 2
0
        //关闭窗口前
        private void AutoUpdateFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Process[] appProcess = Process.GetProcessesByName("在线投标工具");
            //防止多次调用主程序
            if (appProcess.Length <= 0)
            {
                //启动 调用更新程序
                string startExe = $@"{AppDomain.CurrentDomain.BaseDirectory}{mainexe}";
                if (File.Exists(startExe))
                {
                    ProcessStartInfo info = new ProcessStartInfo();
                    info.FileName    = startExe;
                    info.Arguments   = "";
                    info.WindowStyle = ProcessWindowStyle.Minimized;
                    Process.Start(info);
                }
            }

            Process[] process = Process.GetProcessesByName("online_bid_autoUpdate");
            foreach (Process prc in process)
            {
                prc.Kill();
                return;
            }
            Application.Exit();//退出应用程序
        }
Esempio n. 3
0
 private static void doStuff()
 {
     Application.SetSuspendState(PowerState.Hibernate, true, true);
     // Shutdown: Process.Start("shutdown", "/s /t 0");
     // Hibernate: Application.SetSuspendState(PowerState.Hibernate, true, true);
     // Logscreen: LockWorkStation();
 }
Esempio n. 4
0
        public void Run()
        {
            var app = new MockApplication();
            var sut = new UI(app);

            Application.Run(sut);
        }
Esempio n. 5
0
        public static void Initialize(string version)
        {
            if (Initialized)
            {
                return;
            }
            Initialized = true;

            Version = version;

            GitHub = new GitHubClient(new ProductHeaderValue("MapleSeed"))
            {
                Credentials = new Credentials(Token.FromBase64())
            };

            try
            {
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
                Application.ThreadException += EventHandlers.ThreadException;

                AppDomain.CurrentDomain.UnhandledException += EventHandlers.UnhandledException;
                System.Windows.Application.Current.DispatcherUnhandledException += EventHandlers.DispatcherUnhandledException;
                //AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) => { CreateBug(eventArgs.Exception); };
            }
            catch { }
        }
Esempio n. 6
0
        private void toggleButton1_Click(object sender, RibbonControlEventArgs e)
        {
            try
            {
                var currentCursor = Cursor.Current;
                Cursor.Current = Cursors.WaitCursor;
                Application.DoEvents();
                if (this.monitorPane == null)
                {
                    this.monitorPane = ThisAddIn.thisAddIn.CustomTaskPanes.Add(new AttachmentUserControl(), "Вложения");
                    this.monitorPane.VisibleChanged += (s, ea) =>
                    {
                        if (this.thisRibbon != null)
                        {
                            this.thisRibbon.Invalidate();
                        }
                    };

                    this.monitorPane.DockPosition = MsoCTPDockPosition.msoCTPDockPositionLeft;
                    this.monitorPane.Width        = 370;
                }

                this.monitorPane.Visible = !this.monitorPane.Visible; // Visiblethis.MonitorToggleButton.Checked;
                Cursor.Current           = currentCursor;
            }
            catch (Exception ex)
            {
                var message = string.Format("Ошибка запуска: {0}", ex.Message);
                MessageBox.Show(message, @"Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public TestContext()
            : base()
        {
            try
            {
                if (!SboApp.ApplicationConnected)
                {
                    throw new Exception("SboApp not Connected");
                }


                //Test_CopyTo();

                //Test_Form();
                //Test_MenuCreate();
                //Test_GetString();
                //Test_Setting();
                //Test_SettingAsk();
                //Test_FileDialogs();
                Test_SendMessage();
            }
            catch (Exception e)
            {
                MessageBox.Show($"Error: {e.Message}\nExiting...");
                Application.Exit();
            }
        }
Esempio n. 8
0
        private static void openUI()
        {
            _trayIcon.Visible = false;

            var ui = new BackgroundManagerUI.MainWindow();

            //*-------copy data--------*/
            ui.InitializeComponent();

            ui.Data        = Handle.data;
            ui.DataContext = ui.Data;

            ui.loadNonBindings();
            //*------------------------*/

            ui.ShowDialog();

            _trayIcon.Visible = true;

            if (ui.IsToClose)
            {
                WinFormApplication.Exit();
            }

            ui = null;
        }
Esempio n. 9
0
        private void OnExit(object sender, EventArgs e)
        {
            _core.EndService();

            _trayIcon.Visible = false;
            Self.Exit();
        }
Esempio n. 10
0
        /// <summary>
        /// Show the Open File dialogue, then load the selected character.
        /// </summary>
        private void OpenFile(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter      = "Chummer5 Files (*.chum5)|*.chum5|All Files (*.*)|*.*",
                Multiselect = true
            };

            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                Timekeeper.Start("load_sum");
                Cursor = Cursors.WaitCursor;
                Character[] lstCharacters     = new Character[openFileDialog.FileNames.Length];
                object      lstCharactersLock = new object();
                Parallel.For(0, lstCharacters.Length, i =>
                {
                    Character objLoopCharacter = LoadCharacter(openFileDialog.FileNames[i]);
                    lock (lstCharactersLock)
                        lstCharacters[i] = objLoopCharacter;
                });
                Cursor = Cursors.Default;
                Program.MainForm.OpenCharacterList(lstCharacters);
                Application.DoEvents();
                Timekeeper.Finish("load_sum");
                Timekeeper.Log();
            }
        }
Esempio n. 11
0
 /// <summary>
 /// 休眠
 /// </summary>
 /// <param name="ResultArray"></param>
 /// <param name="MessageResult"></param>
 public static void PM_Hibernation(ref Dictionary <string, object> ResultArray, ref string MessageResult)
 {
     ResultArray[Parameters.Status] = "Pass";
     MessageResult = dll_PublicFuntion.Other.DictionaryToXml(ResultArray);
     Program.SSend(Parameters.ServerSocket.SClient, MessageResult);
     Application.SetSuspendState(PowerState.Hibernate, true, true);
 }
 private static void Main()
 {
     if (!IsAdministrator())
     {
         var info = new ProcessStartInfo(Assembly.GetExecutingAssembly().GetName().Name);
         info.Verb = "runas";
         Process.Start(info);
         Application.Exit();
     }
     else
     {
         AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         try
         {
             Application.Run(new MainForm());
         }
         catch (Exception ex)
         {
             TraceHelper.Tracer.WriteTrace(ex.ToString());
             MessageBox.Show(ex.ToString());
         }
     }
 }
Esempio n. 13
0
        static void Main(string[] args)
        {
            try
            {
                HighlightingManager.Manager.AddSyntaxModeFileProvider(
                    new SyntaxEditor());

                if (ConfigHelper.IsStandalone)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new PringManagerForm());
                }
                else
                {
                    app = Nampula.UI.Application.GetInstance();

                    app.OnStartCreateMenu += App_OnStartCreateMenu;
                    app.OnStartConnection += App_OnStartConnection;
                    app.OnShutDown        += App_OnShutDown;

                    if (app.StartApplication("LP", Nampula.UI.eAppType.SAPForms))
                    {
                        var mainForm = app.MainForm();
                        Application.Run(mainForm);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Application"/> class.
        /// </summary>
        protected Application(ApplicationContext settings)
            : base(settings)
        {
            Settings = settings;

            var uiSynchronizationContextCreated = new AutoResetEvent(false);

            UiThread = new Thread(() =>
            {
                FormsApplication.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                FormsApplication.ThreadException           += new ThreadExceptionEventHandler(Forms_UiUnhandledException);
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(Forms_UnhandledException);

                FormsApplication.EnableVisualStyles();
                FormsApplication.SetCompatibleTextRenderingDefault(false);

                SynchronizationContext.SetSynchronizationContext(UiSynchronizationContext = new WindowsFormsSynchronizationContext());
                uiSynchronizationContextCreated.Set();

                FormsApplication.Run();
            });
            UiThread.SetApartmentState(ApartmentState.STA);
            UiThread.Start();

            uiSynchronizationContextCreated.WaitOne();
        }
Esempio n. 15
0
        private void cmdRestart_Click(object sender, EventArgs e)
        {
            Log.Info("cmdRestart_Click");
            if (Directory.Exists(_strAppPath) && File.Exists(_strTempPath))
            {
                cmdUpdate.Enabled  = false;
                cmdRestart.Enabled = false;
                //Create a backup file in the temp directory.
                string strBackupZipPath = Path.Combine(Path.GetTempPath(), "chummer" + CurrentVersion + ".zip");
                Log.Info("Creating archive from application path: ", _strAppPath);
                if (!File.Exists(strBackupZipPath))
                {
                    ZipFile.CreateFromDirectory(_strAppPath, strBackupZipPath, CompressionLevel.Fastest, true);
                }
                // Delete the old Chummer5 executable.
                if (File.Exists(_strAppPath + "\\" + AppDomain.CurrentDomain.FriendlyName + ".old"))
                {
                    File.Delete(_strAppPath + "\\" + AppDomain.CurrentDomain.FriendlyName + ".old");
                }
                // Rename the current Chummer5 executable.
                File.Move(_strAppPath + "\\" + AppDomain.CurrentDomain.FriendlyName, _strAppPath + "\\" + AppDomain.CurrentDomain.FriendlyName + ".old");
                foreach (string strLoopDllName in Directory.GetFiles(_strAppPath, "*.dll"))
                {
                    if (File.Exists(strLoopDllName + ".old"))
                    {
                        File.Delete(strLoopDllName + ".old");
                    }
                    File.Move(strLoopDllName, strLoopDllName + ".old");
                }

                // Copy over the archive from the temp directory.
                Log.Info("Extracting downloaded archive into application path: ", _strTempPath);
                using (ZipArchive archive = ZipFile.Open(_strTempPath, ZipArchiveMode.Read, Encoding.GetEncoding(850)))
                {
                    foreach (ZipArchiveEntry entry in archive.Entries)
                    {
                        // Skip directories because they already get handled with Directory.CreateDirectory
                        if (entry.FullName.Length > 0 && entry.FullName[entry.FullName.Length - 1] == '/')
                        {
                            continue;
                        }
                        string strLoopPath = Path.Combine(_strAppPath, entry.FullName);
                        try
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(strLoopPath));
                            entry.ExtractToFile(strLoopPath, true);
                        }
                        catch (UnauthorizedAccessException)
                        {
                            MessageBox.Show(LanguageManager.Instance.GetString("Message_Insufficient_Permissions_Warning"));
                            break;
                        }
                    }
                }
                Log.Info("Restart Chummer");
                Application.Restart();
                cmdUpdate.Enabled  = true;
                cmdRestart.Enabled = true;
            }
        }
Esempio n. 16
0
        private async Task InitSession()
        {
            try
            {
                StatusText = "Inititializing session...";
                await osdbClient.InitSessionAsync();
            }
            catch (OSDbException e)
            {
                var result = MessageBox.Show(
                    $"Failed to initialize session: {e.Message}",
                    "Error",
                    MessageBoxButtons.RetryCancel,
                    MessageBoxIcon.Error);

                if (result == DialogResult.Retry)
                {
                    await InitSession();
                }
                else
                {
                    Application.Exit();
                }
            }

            StatusText = "Session initialized.";
        }
Esempio n. 17
0
 private void Exit()
 {
     trayIcon.Visible = false;
     muteForm.SaveSettings();
     muteForm.Close();
     WinFormsApplication.Exit();
 }
Esempio n. 18
0
        public AddinModule()
        {
            Application.EnableVisualStyles();

            InitializeComponent();
            // Please add any initialization code to the AddinInitialize event handler
        }
        private void BtnRetry_OnClick(object sender, RoutedEventArgs e)
        {
            IRestaurantService service = new RestaurantServiceImpl();
            var result = service.GetUnclearnPosInfo();

            if (!string.IsNullOrEmpty(result.Item1))
            {
                frmWarning.ShowWarning(result.Item1);
                return;
            }

            var noClearnMachineList = result.Item2;

            if (noClearnMachineList.Any()) //这里只需要判断有未清机的就不关闭窗口。
            {
                return;
            }

            string reinfo;

            if (!RestClient.OpenUp("", "", 0, out reinfo))//如果判断未开业则说明结业成功了。
            {
                Application.Exit();
            }

            DialogResult = true;
            Close();
        }
Esempio n. 20
0
        private void ExitMenu_Click(object sender, EventArgs e)
        {
            Dispose();
            Startup.DisposeOutlookObjects();

            Application.Exit();
        }
Esempio n. 21
0
        private void InitializeTrayIcon()
        {
            _trayMenu = new ContextMenu();

            var item = new MenuItem("Auto Start");

            item.Checked = AutoStart();
            item.Click  += OnAutoStartClick;
            _trayMenu.MenuItems.Add(item);

            _trayMenu.MenuItems.Add("Reset", OnResetClickedOnClick);
            _trayMenu.MenuItems.Add("-");
            _trayMenu.MenuItems.Add("Exit", (sender, args) => Application.Exit());

            components = new Container();

            _trayIcon = new NotifyIcon(components)
            {
                Text        = "SoftU2F Daemon",
                ContextMenu = _trayMenu,
                Icon        = new Icon("tray.ico"),
                Visible     = true
            };

            _trayIcon.BalloonTipClicked += (sender, args) =>
            {
                _notificationOpen = false;
                _userPresenceCallback?.Invoke(true);
            };
            _trayIcon.BalloonTipShown  += (sender, args) => _notificationOpen = true;
            _trayIcon.BalloonTipClosed += (sender, args) => _notificationOpen = false;
        }
Esempio n. 22
0
        public void Completato(object o, AsyncCompletedEventArgs args)
        {
            log("Disinstallando la vecchia versione...[0%]");
            log("Disinstallata la vecchia verisone[40%]");

            MessageBox.Show("Disintallando la vecchia versione", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            string app_name = ApplicationForm.StartupPath + "\\" + ApplicationForm.ProductName + ".exe";
            string bat_name = app_name + ".bat";

            string bat =
                "@echo off\n"                                                                                          //CHECK BEFORE RELEASE
                + ":loop\n"
                + "del \"" + app_name + "\"\n"
                + "if Exist \"" + app_name + "\" GOTO loop\n"
                + "ren PercentualeAlunni_new.exe PercentualeAlunni.exe\n"
                + "del %0\n"
                + "start PercentualeAlunni.exe";

            StreamWriter file = new StreamWriter(bat_name);

            file.Write(bat);
            file.Close();

            Process bat_call = new Process();

            bat_call.StartInfo.FileName        = bat_name;
            bat_call.StartInfo.WindowStyle     = ProcessWindowStyle.Hidden;
            bat_call.StartInfo.UseShellExecute = true;
            bat_call.Start();

            log("Disinstallata la vecchia verisone[100%]");
            log("Download terminato.");

            ApplicationForm.Exit();
        }
Esempio n. 23
0
        public static Form ShowXamarinControl(this ContentPage ctl, int Width, int Height)
        {
            var f = new Xamarin.Forms.Platform.WinForms.PlatformRenderer();

            Xamarin.Forms.Platform.WinForms.Forms.Init(f);

            f.Width  = Width;
            f.Height = Height;
            var done = false;

            Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
            {
                var app = new Xamarin.Forms.Application()
                {
                    MainPage = ctl
                };
                f.LoadApplication(app);
                ThemeManager.ApplyThemeTo(f);
                if (ctl is IClose)
                {
                    ((IClose)ctl).CloseAction = () => f.Close();
                }

                f.ShowDialog();
                done = true;
            });

            while (!done)
            {
                Application.DoEvents();
            }

            return(f);
        }
Esempio n. 24
0
        private void messBox()
        {
            var message = "Voulez vous recommencer ?";
            var title   = "Hey!";
            var result  = MessageBox.Show(
                message,
                title,
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question);

            switch (result)
            {
            case DialogResult.Yes:
                iniform();
                Form1_Load();
                break;

            case DialogResult.No:
                Application.Exit();
                break;

            default:
                MessageBox.Show("What did you press?");
                break;
            }
        }
Esempio n. 25
0
 static void Main()
 {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
     Application.Run(new Form1());
 }
Esempio n. 26
0
        static void Main()
        {
            string appdata        = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string productDataDir = Directory.CreateDirectory(MainApplication.ProductName).Name;
            string dataDir        = Path.Combine(appdata, productDataDir);

            Directory.CreateDirectory(dataDir);
            AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            var success = true;

            try
            {
                AppDomain.CurrentDomain.SetData("ConnectionString", ConfigurationManager.ConnectionStrings["SettingsDatabase"].ConnectionString);
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was a problem while loading the config file: " + ex.Message);
                success = false;
            }

            if (success)
            {
                MainApplication.EnableVisualStyles();
                MainApplication.SetCompatibleTextRenderingDefault(false);
                MainApplication.Run(new ChurchTimer.Presentation.ControlPanel());
            }
        }
 void OtherMachineNoClearnWarningWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
 {
     if (DialogResult != true)
     {
         Application.Exit();
     }
 }
Esempio n. 28
0
        private void allToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CommonOpenFileDialog m = new CommonOpenFileDialog();

            m.IsFolderPicker   = true;
            m.EnsurePathExists = true;
            m.Title            = "Select Folder to Output to";
            if (m.ShowDialog() == CommonFileDialogResult.Ok)
            {
                string dir = m.FileName;
                for (int i = 0; i < entr.Count; i++)
                {
                    Entry      t          = entr[i];
                    string     filePath   = Path.Combine(dir, t.off.ToString("X") + ".bik");
                    FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                    listBox2.Items.Add("Extracting " + filePath);
                    listBox2.SelectedIndex = listBox2.Items.Count - 1;
                    Application.DoEvents();
                    for (int j = 0; j < t.size; j++)
                    {
                        fileStream.WriteByte(memory[t.off + j]);
                    }
                    fileStream.Close();
                }
                MessageBox.Show("Done.");
            }
        }
Esempio n. 29
0
        private static void ShowCrashDialog(Exception ex)
        {
            string msg    = ex == null ? "Unexpected error" : $"An error occurred: {ex.Message}";
            string detail = ex == null ? "" : ex.ToString();

            MessageBox.Show(text: $"{msg}\n\nPlease report this error at {ProgramInfo.GithubUrl}\n\nError details:\n\n{detail}", caption: "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            WinFormsApplication.Exit();
        }
Esempio n. 30
0
 static void Main()
 {
     client.SetSecurity();
     client.LoginAsync().Wait();
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new Form1());
 }
Esempio n. 31
0
        private static int Run(Application Instance,IntPtr l)
        {
            // get method arguments
                  int mainFormId = (int)LuaApi.lua_tonumber(l,3);
                  Form mainForm = LuaManager.Instance.GetObjectT<Form>(mainFormId);

                  // call method
                  Application.Run(mainForm);

                  return 0;
        }
Esempio n. 32
0
		async void samplesListbox_SelectedIndexChanged(object sender, EventArgs e)
		{
			currentApplication?.Engine.Exit();
			currentApplication = null;
			await semaphoreSlim.WaitAsync();
			var type = (Type) samplesListbox.SelectedItem;
			if (type == null) return;
			urhoSurfacePlaceholder.Controls.Clear(); //urho will destroy previous control so we have to create a new one
			var urhoSurface = new Panel { Dock = DockStyle.Fill };
			urhoSurfacePlaceholder.Controls.Add(urhoSurface);
			await Task.Delay(100);//give some time for GC to cleanup everything
			currentApplication = Application.CreateInstance(type, new ApplicationOptions("Data") { ExternalWindow = urhoSurface.Handle });
			urhoSurface.Focus();
			currentApplication.Run();
			semaphoreSlim.Release();
		}
		// 新しくプロジェクトが開かれたとき、プロジェクトのバーチャルシェイプを登録する。
		public override void Application_OpenedProjectChanged(object sender, Application.OpenedProjectChangedEventArgs e)
			{
			if( Application_OpenedProjectChanged_Running ) return;
			Application_OpenedProjectChanged_Running = true;

			if( e.NewItem != null )
				{
				Application.ValidateProject( Application.DoesUpdateShapeAuto );
				viewer.VirtualGraphics = Application.VirtualGraphics;
				viewer.VirtualGraphics.Mirroring = new SizeD( 1, -1 );
				viewer.VirtualGraphics.AxesLine = Pens.White;
				viewer.MoveViewToPerspective( PerspectivePadding );
				}
			else
				viewer.VirtualGraphics = null;

			Application_OpenedProjectChanged_Running = false;
			}
Esempio n. 34
0
        public static void Main(string[] Args)
        {
            try
            {
                AppDomain currentDomain = AppDomain.CurrentDomain;
                currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

                mutex = new Mutex(true, identifier, out isNotRunning);
                if (isNotRunning)
                {
                    System.Windows.Forms.Application.EnableVisualStyles();
                    System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);

                    System.Windows.Forms.Application.ApplicationExit += new EventHandler(Application_ApplicationExit);

                    application = Application.CreateInstance();
                    if (application != null)
                    {
                        application.OnExit += new EventHandler(application_OnExit);
                        application.Initialize();

                        frm = new MainForm(application);
                        frm.FormClosed += new FormClosedEventHandler(frm_FormClosed);

                        if (application.isNotify)
                        {
                            frm.ShowInTaskbar = false;
                            frm.WindowState = FormWindowState.Minimized;
                        }

                        System.Windows.Forms.Application.Run(frm);
                    }
                }
                else
                {
                    // 13.02.2013 - убрано, так как повторный запуск стал нормальным явлением!
                    //MessageBox.Show("Приложение уже запущено", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            finally
            {
            }
        }
Esempio n. 35
0
        internal static void LoadCommandBars(XmlNode xmlCustomUI, GetImageDelegate getImage)
        {
            if (xmlCustomUI.NamespaceURI != "http://schemas.excel-dna.net/office/2003/01/commandbars")
            {
                // Unsupported version ....
                // TODO: Log display ....?
                Debug.Print("Unsupported commandBars version.");
                return;
            }

            Application excelApp = new Application(ExcelDnaUtil.Application);

            loadedCustomUIs.Add(xmlCustomUI);
            try
            {
                AddCommandBarControls(excelApp, xmlCustomUI.ChildNodes, getImage);
            }
            catch (Exception e)
            {
                // Suppress exceptions
                Debug.Print("ExcelCommandBars: Error adding controls: {0}", e);
            }
        }
 public static void RegisterMessageLoop(Application.MessageLoopCallback callback);
Esempio n. 37
0
 public void UseTemplate(string path, string templatePath, string[,] myTemplateValues)
 {
     try
     {
         this.string_0 = myTemplateValues;
         this.application_0 = new ApplicationClass();
         this.workbook_0 = this.application_0.get_Workbooks().Open(templatePath, 0, false, 5, "", "", false, (XlPlatform) 2, "", true, false, 0, true, false, false);
         this.sheets_0 = this.workbook_0.get_Sheets();
         this.worksheet_0 = (Worksheet) this.sheets_0.get_Item(1);
         this.worksheet_0.set_Name("ATemplate");
         this.method_5();
         this.method_4();
         try
         {
             this.method_7(this.sheets_0);
             this.method_7(this.worksheet_0);
             this.workbook_0.Close(true, path, Type.Missing);
             this.method_7(this.workbook_0);
             this.application_0.set_UserControl(false);
             this.application_0.Quit();
             this.method_7(this.application_0);
             this.method_6();
             ProgressEventArgs e = new ProgressEventArgs(100);
             this.OnProgressChange(e);
         }
         catch (COMException)
         {
             Console.WriteLine("用户手动关闭了Excel程序,导出操作不成功");
         }
     }
     catch (Exception exception)
     {
         MessageBox.Show("错误 " + exception.Message);
     }
 }
Esempio n. 38
0
 public void ExportToExcel(List<DataView> dvList, string path, string sheetName)
 {
     Exception exception;
     try
     {
         int num;
         int num2;
         this.list_0 = dvList;
         this.application_0 = new ApplicationClass();
         if (File.Exists(path))
         {
             this.workbook_0 = this.application_0.get_Workbooks().Open(path, 0, false, 5, "", "", false, (XlPlatform) 2, "", true, false, 0, true, false, false);
             this.sheets_0 = this.workbook_0.get_Sheets();
             num = -1;
             for (num2 = 1; num2 <= this.sheets_0.get_Count(); num2++)
             {
                 this.worksheet_0 = (Worksheet) this.sheets_0.get_Item(num2);
                 if (this.worksheet_0.get_Name().ToString().Equals(sheetName))
                 {
                     num = num2;
                     Range range = this.worksheet_0.get_Cells();
                     range.Select();
                     range.get_CurrentRegion().Select();
                     range.ClearContents();
                 }
             }
             if (num == -1)
             {
                 ((Worksheet) this.workbook_0.get_Sheets().Add(Type.Missing, (Worksheet) this.sheets_0.get_Item(this.sheets_0.get_Count()), Type.Missing, Type.Missing)).set_Name(sheetName);
             }
         }
         else
         {
             this.workbook_0 = this.application_0.get_Workbooks().Add((XlWBATemplate) (-4167));
             this.sheets_0 = this.workbook_0.get_Sheets();
             this.worksheet_0 = (Worksheet) this.sheets_0.get_Item(1);
             this.worksheet_0.set_Name(sheetName);
         }
         this.sheets_0 = this.workbook_0.get_Sheets();
         num = -1;
         for (num2 = 1; num2 <= this.sheets_0.get_Count(); num2++)
         {
             this.worksheet_0 = (Worksheet) this.sheets_0.get_Item(num2);
             if (this.worksheet_0.get_Name().ToString().Equals(sheetName))
             {
                 num = num2;
             }
         }
         this.worksheet_0 = (Worksheet) this.sheets_0.get_Item(num);
         this.method_0();
         this.method_1();
         this.method_4();
         try
         {
             this.method_7(this.sheets_0);
             this.method_7(this.worksheet_0);
             this.workbook_0.Close(true, path, Type.Missing);
             this.method_7(this.workbook_0);
             this.application_0.set_UserControl(false);
             this.application_0.Quit();
             this.method_7(this.application_0);
             this.method_6();
             ProgressEventArgs e = new ProgressEventArgs(100);
             this.OnProgressChange(e);
         }
         catch (COMException)
         {
             MessageBox.Show("用户手动关闭了Excel程序,导出操作不成功");
         }
         catch (Exception exception2)
         {
             exception = exception2;
             MessageBox.Show("错误 " + exception.Message);
         }
     }
     catch (Exception exception3)
     {
         exception = exception3;
         MessageBox.Show("错误 " + exception.Message);
     }
 }
        private static void RemoveCommandBarControls(Application excelApp, XmlNodeList xmlNodes)
        {
            foreach (XmlNode childNode in xmlNodes)
            {
                if (childNode.Name == "commandBar")
                {
                    string barName = childNode.Attributes["name"].Value;
                    CommandBar bar = null;
                    for (int i = 1; i <= excelApp.CommandBars.Count; i++)
                    {
                        if (excelApp.CommandBars[i].Name == barName)
                        {
                            bar = excelApp.CommandBars[i];
                            break;
                        }
                    }
                    if (bar != null)
                    {
                        RemoveControls(bar.Controls, childNode.ChildNodes);

                        if (bar.Controls.Count() == 0)
                        {
                            bar.Delete();
                        }
                    }
                }
            }
        }
		// アプリケーションセレクションが変更されたとき、描画色の処理を行う。
		public override void Application_SelectionChanged(object sender, Application.SelectionChangedEventArgs e)
			{
			Application.ValidateGeometricObjects( false );
			RefreshRender();
			}
		// ジオメトリックオブジェクトの式にエラーが含まれているときに実行される。
		public override void Application_GeometricObjectInvalid(object sender, Application.GeometricObjectInvalidEventArgs e)
			{
			toolStripStatusLabel02.Text = e.ErrordObject.Name + " is invalid.";
			}
		public virtual void Application_SelectionChanged(object sender, Application.SelectionChangedEventArgs e) { }
		public virtual void Application_GeometricObjectInvalid(object sender, Application.GeometricObjectInvalidEventArgs e) { }
 internal void RegisterMessageLoop(Application.MessageLoopCallback callback)
 {
     this.messageLoopCallback = callback;
 }
		public virtual void Application_OpenedProjectChanged(object sender, Application.OpenedProjectChangedEventArgs e) { }
Esempio n. 46
0
        private static void RemoveCommandBarControls(Application excelApp, XmlNodeList xmlNodes)
        {
            foreach (XmlNode childNode in xmlNodes)
            {
                if (childNode.Name == "commandBar")
                {
                    string barName;
                    CommandBar bar = GetCommandBarFromIdOrName(excelApp, childNode.Attributes, out barName);
                    if (bar != null)
                    {
                        RemoveControls(bar.Controls, childNode.ChildNodes);

                        if (bar.Controls.Count() == 0)
                        {
                            bar.Delete();
                        }
                    }
                }
            }
        }
Esempio n. 47
0
        public static void UnloadCommandBars()
        {
            if (loadedCustomUIs == null || loadedCustomUIs.Count == 0)
            {
                // Nothing to do.
                return;
            }
            Application excelApp = new Application(ExcelDnaUtil.Application);
            foreach (XmlNode xmlCustomUI in loadedCustomUIs)
            {
                try
                {
                    RemoveCommandBarControls(excelApp, xmlCustomUI.ChildNodes);
                }
                catch (Exception e)
                {
                    // Suppress exceptions
                    Debug.Print("ExcelCommandBars: Error removing controls: {0}", e);
                }

            }
            loadedCustomUIs.Clear();
        }
Esempio n. 48
0
        public async Task<bool> CreateDDPalReportAsync(string FilePath)
        {
            Trace.TraceInformation("Rudy Trace =>CreateDDPalReportAsync: Report Path = " + FilePath);
            bool bRet = await Task.Run(() =>
            {
                try
                {
                    Application excel = new Application();
                    excel.Visible = false;
                    Workbook wb = excel.Workbooks.Add();
                    Worksheet ws = wb.Sheets[1] as Worksheet;

                    ws.Cells[1, 1] = "账户";
                    ws.Cells[1, 2] = "密码";
                    ws.Cells[1, 3] = "订单编号";
                    ws.Cells[1, 4] = "数量";
                    ws.Cells[1, 5] = "金额(元)";
                    ws.Cells[1, 6] = "备注";
                    ws.Cells[1, 7] = "已评论";
                    for (int i = 1; i < 8; i++)
                    {
                        ((Range)(ws.Cells[1, i])).HorizontalAlignment = XlHAlign.xlHAlignLeft;
                        ((Range)(ws.Cells[1, i])).ColumnWidth = 12;
                    }

                    wb.SaveAs(FilePath);

                    if (wb != null)
                        wb.Close();
                    if (excel != null)
                    {
                        excel.Quit();
                        App.KillExcel(excel);
                        excel = null;
                    }
                }
                catch (Exception e)
                {
                    System.Windows.MessageBox.Show(e.Message, Globals.JD_CAPTION);
                    Trace.TraceInformation("Rudy Exception=> CreateDDPalReportAsync: " + e.Source + ";" + e.Message);
                    return false;
                }

                return true;
            }).ConfigureAwait(false);
            return bRet;
        }
		// アプリケーションにおいて選択オブジェクトが変更されたときに実行する
		public override void Application_SelectionChanged(object sender, Application.SelectionChangedEventArgs e)
			{
			if( Application_SelectionChanged_Running ) return;
			Application_SelectionChanged_Running = true;
			treeView.SuspendLayout();

			bool flag = true;
			foreach( TreeNode node in GetAllNode() )
				if( node.Tag == Application.Selection )
					{
					treeView.SelectedNode = node;
					flag = false;
					break;
					}
			if( flag ) treeView.SelectedNode = null;

			treeView.ResumeLayout();
			Application_SelectionChanged_Running = false;
			}
Esempio n. 50
0
        // This method contributed by Benoit Patra (see GitHub pull request: https://github.com/Excel-DNA/Excel-DNA/pull/1)
        // TODO: Still need to sort out the Id property
        //       This version is temporary, should behave the same as v.0.32
        private static CommandBar GetCommandBarFromIdOrName(Application excelApp, XmlAttributeCollection nodeAttributes, out string barName)
        {
            XmlAttribute name = nodeAttributes["name"];
            if (name == null) throw new ArgumentException("CommandBar attributes must contain name");
            barName = name.Value;

            CommandBar bar = null;
            for (int i = 1; i <= excelApp.CommandBars.Count; i++)
            {
                if (excelApp.CommandBars[i].Name == barName)
                {
                    bar = excelApp.CommandBars[i];
                    break;
                }
            }
            return bar;
        }
Esempio n. 51
0
        public async Task<bool> UpdateDDPalReportAsync(string FilePath, int AccountNo, bool bSuccess)
        {
            bool bRet = await Task.Run(() =>
            {
                try
                {
                    Application excel = new Application();
                    excel.Visible = false;
                    Workbook wb = excel.Workbooks.Open(FilePath);
                    Worksheet ws = wb.ActiveSheet as Worksheet;

                    int nRow = AccountNo + 1;
                    int nAccountIndex = AccountNo - 1;

                    for (int i = 1; i < 8; i++)
                    {
                        ((Range)(ws.Cells[nRow, i])).HorizontalAlignment = XlHAlign.xlHAlignLeft;
                    }

                    ws.Cells[nRow, 1] = aJDAccount[nAccountIndex].UserName;
                    ws.Cells[nRow, 2] = aJDAccount[nAccountIndex].Password;
                    if (bSuccess)
                    {
                        ws.Cells[nRow, 3] = OrderNo;
                        ws.Cells[nRow, 4] = SinglePalCount;
                        ws.Cells[nRow, 5] = OrderMoney;
                        ws.Cells[nRow, 6] = Settings.Default.Remark;
                        ws.Cells[nRow, 7] = "否";
                    }
                    else
                    {
                        ((Range)(ws.Cells[nRow, 1])).Interior.ColorIndex = 3;
                        ((Range)(ws.Cells[nRow, 2])).Interior.ColorIndex = 3;
                    }
                    
                    wb.Save();

                    if (wb != null)
                        wb.Close();
                    if (excel != null)
                    {
                        excel.Quit();
                        App.KillExcel(excel);
                        excel = null;
                    }
                }
                catch (Exception e)
                {
                    System.Windows.MessageBox.Show(e.Message, Globals.JD_CAPTION);
                    Trace.TraceInformation("Rudy Exception=> UpdateDDPalReportAsync: " + e.Source + ";" + e.Message);
                    return false;
                }

                return true;
            }).ConfigureAwait(false);
            return bRet;
        }
Esempio n. 52
0
 // Helper to call Application.CommandBars
 public static CommandBars GetCommandBars()
 {
     Application excelApp = new Application(ExcelDnaUtil.Application);
     return excelApp.CommandBars;
 }
Esempio n. 53
0
        public async Task<bool> SetAddressAccoutInfoAsync(string FilePath)
        {
            bool bRet = await Task.Run(() =>
            {
                if (aAccountInfo != null)
                    aAccountInfo.Clear();
                try
                {
                    Application excel = new Application();
                    excel.Visible = false;
                    Workbook wb = excel.Workbooks.Open(FilePath);
                    Worksheet ws = wb.ActiveSheet as Worksheet;
                    int nRowCount = ws.UsedRange.Cells.Rows.Count;//get the used rows count.

                    AccountInfo infoTemp;
                    for (int i = 2; i <= nRowCount; i++)
                    {
                        infoTemp.Account = ((Range)ws.Cells[i, 1]).Text;
                        infoTemp.Password = ((Range)ws.Cells[i, 2]).Text;
                        infoTemp.FullName = ((Range)ws.Cells[i, 3]).Text;
                        infoTemp.Mobile = ((Range)ws.Cells[i, 4]).Text;
                        infoTemp.Province = ((Range)ws.Cells[i, 5]).Text;
                        infoTemp.City = ((Range)ws.Cells[i, 6]).Text;
                        infoTemp.County = ((Range)ws.Cells[i, 7]).Text;
                        infoTemp.Town = ((Range)ws.Cells[i, 8]).Text;
                        infoTemp.DetailAddress = ((Range)ws.Cells[i, 9]).Text;
                        aAccountInfo.Add(infoTemp);
                    }
                    if (wb != null)
                        wb.Close();
                    if (excel != null)
                    {
                        excel.Quit();
                        App.KillExcel(excel);
                        excel = null;
                    }
                }
                catch (Exception e)
                {
                    System.Windows.MessageBox.Show(e.Message, Globals.JD_CAPTION);
                    Trace.TraceInformation("Rudy Exception=> SetAddressAccoutInfoAsync: " + e.Source + ";" + e.Message);
                    return false;
                }

                return true;
            }).ConfigureAwait(false);
            return bRet;
        }
Esempio n. 54
0
        private static void AddCommandBarControls(Application excelApp, XmlNodeList xmlNodes, GetImageDelegate getImage)
        {
            foreach (XmlNode childNode in xmlNodes)
            {
                if (childNode.Name == "commandBar")
                {
                    string barName;
                    CommandBar bar = GetCommandBarFromIdOrName(excelApp, childNode.Attributes, out barName);
                    if (bar != null)
                    {
                        AddControls(bar.Controls, childNode.ChildNodes, getImage);
                    }
                    else
                    {
                        MsoBarPosition barPosition = MsoBarPosition.msoBarLeft;
                        XmlAttribute posAttribute = childNode.Attributes["position"];
                        if (posAttribute == null)
                        {
                            // Compatible with original patch
                            posAttribute = childNode.Attributes["MsoBarPosition"];
                        }
                        if (posAttribute != null)
                        {
                            if (Enum.IsDefined(typeof(MsoBarPosition), posAttribute.Value))
                                barPosition = (MsoBarPosition)Enum.Parse(typeof(MsoBarPosition), posAttribute.Value, false);
                        }

                        bar = excelApp.CommandBars.Add(barName, barPosition);
                        AddControls(bar.Controls, childNode.ChildNodes, getImage);
                    }

                }
            }
        }
 private void EnableThreadWindowsCallback(Application.ThreadContext context, bool onlyWinForms)
 {
     context.EnableWindowsForModalLoop(onlyWinForms, this);
 }