예제 #1
1
 public static bool Show(string title, string caption, ref string value, Predicate<string> predicate = null)
 {
     using (var inputBox = new InputBox())
     {
         inputBox.Text = title;
         inputBox.lciText.Text = caption;
         inputBox.lciMemo.Visibility = LayoutVisibility.Never;
         inputBox._predicate = predicate;
         inputBox.Height = 140;
         inputBox.txtMessage.EditValue = value ?? string.Empty;
         var dr = inputBox.ShowDialog();
         if (dr == DialogResult.OK)
         {
             value = inputBox.txtMessage.EditValue.ToStringEx();
             inputBox._predicate = null;
             return true;
         }
         else
         {
             value = string.Empty;
             inputBox._predicate = null;
             return false;
         }
     }
 }
예제 #2
1
        public static string AskValue(IWin32Window owner, string caption = "InputBox", string description = "Insert a new value.", string value = "")
        {
            InputBox input = new InputBox();
            string ret = "";

            try
            {
                input.Text = caption;

                input.lbDescription.Text = description;
                input.txValue.Text = value;

                input.ShowDialog(owner);
                if (input.DialogResult == System.Windows.Forms.DialogResult.OK)
                {
                    ret = input.txValue.Text;
                }
                input.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.GetType().FullName, ex.Message);
            }

            return ret;
        }
예제 #3
0
        public void Reinit()
        {
            /* Reset the form labels */
            lblSongTitle.TextAlign = ContentAlignment.TopCenter;
            lblSongTitle.Text = "Nothing Playing";
            lblSongAlbum.Text = "";
            lblSongArtist.Text = "";
            coolProgressBar1.Visible = false;
            originalIcon = this.Icon;

            lblUserName.Visible = Properties.Settings.Default.showExtraInfo;
            lblRoomName.Visible = Properties.Settings.Default.showExtraInfo;

            if (Properties.Settings.Default.promptForPassword) {
                InputBox tmp = new InputBox();
                DialogResult _result = tmp.ShowDialog(this);
                if (_result == DialogResult.OK) {
                    _password = tmp.Password;
                }
            }

            /* Send the initial login request */
            Thread _worker = new Thread(new ThreadStart(doLogin));
            _worker.Name = "Login Thread";
            _worker.Start();
        }
 public override void Run()
 {
     if (this.IsEnabled)
     {
         InputBox box = new InputBox("请输入使用的远程服务自动升级对象地址:", "提示:", "http://127.0.0.1:7502/RemoteUpdate");
         string result = string.Empty;
         if (box.ShowDialog(WorkbenchSingleton.MainForm) == DialogResult.OK)
         {
             result = box.Result;
             if (string.IsNullOrEmpty(result))
             {
                 MessageHelper.ShowInfo("没有输入远程对象地址");
             }
             else
             {
                 try
                 {
                     (Activator.GetObject(typeof(IRemoteUpdate), result) as IRemoteUpdate).Execute();
                     MessageHelper.ShowInfo("远程服务执行升级操作成功!");
                 }
                 catch (Exception exception)
                 {
                     MessageHelper.ShowError("远程服务执行升级操作发生错误", exception);
                     LoggingService.Error(exception);
                 }
             }
         }
     }
 }
예제 #5
0
파일: FormSpellCheck.cs 프로젝트: mnisl/OD
		private void gridMain_CellDoubleClick(object sender,ODGridClickEventArgs e) {
			InputBox editWord=new InputBox("Edit word");
			DictCustom origWord=DictCustoms.Listt[e.Row];
			editWord.textResult.Text=origWord.WordText;
			if(editWord.ShowDialog()!=DialogResult.OK) {
				return;
			}
			if(editWord.textResult.Text==origWord.WordText) {
				return;
			}
			if(editWord.textResult.Text=="") {
				DictCustoms.Delete(origWord.DictCustomNum);
				DataValid.SetInvalid(InvalidType.DictCustoms);
				FillGrid();
				return;
			}
			string newWord=Regex.Replace(editWord.textResult.Text,"[\\s]|[\\p{P}\\p{S}-['-]]","");//don't allow words with spaces or punctuation except ' and - in them
			for(int i=0;i<DictCustoms.Listt.Count;i++) {//Make sure it's not already in the custom list
				if(DictCustoms.Listt[i].WordText==newWord) {
					MsgBox.Show(this,"The word "+newWord+" is already in the custom word list.");
					editWord.textResult.Text=origWord.WordText;
					return;
				}
			}
			origWord.WordText=newWord;
			DictCustoms.Update(origWord);
			DataValid.SetInvalid(InvalidType.DictCustoms);
			FillGrid();
		}
 public static void ImportData()
 {
     var dialog = new InputBox("Import Widgets");
     dialog.ShowDialog();
     if (dialog.Cancelled == false &&
         Popup.Show(
             "Are you sure you want to overwrite all current widgets?\n\nThis cannot be undone.",
             MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No) == MessageBoxResult.Yes)
     {
         try
         {
             // Test import data before overwriting existing data.
             foreach (
                 var id in
                     JsonConvert.DeserializeObject<WidgetsSettingsStore>(dialog.InputData, JsonSerializerSettings)
                         .Widgets.Select(x => x.Identifier.Guid))
             {
             }
         }
         catch
         {
             Popup.Show(
                 $"Import failed. Data may be corrupt.{Environment.NewLine}{Environment.NewLine}No changes have been made.",
                 MessageBoxButton.OK, MessageBoxImage.Warning);
             return;
         }
         Settings.Default.Widgets = dialog.InputData;
         Settings.Default.Save();
         LoadWidgetsDataFromSettings();
         WidgetHelper.LoadWidgetViews();
     }
 }
예제 #7
0
        /// <summary>
        /// Displays a prompt in a dialog box, waits for the user to input text or click a button.
        /// </summary>
        /// <param name="prompt">String expression displayed as the message in the dialog box</param>
        /// <param name="title">String expression displayed in the title bar of the dialog box</param>
        /// <param name="defaultResponse">String expression displayed in the text box as the default response</param>
        /// <param name="validator">Delegate used to validate the text</param>
        /// <param name="xpos">Numeric expression that specifies the distance of the left edge of the dialog box from the left edge of the screen.</param>
        /// <param name="ypos">Numeric expression that specifies the distance of the upper edge of the dialog box from the top of the screen</param>
        /// <returns>An InputBoxResult object with the Text and the OK property set to true when OK was clicked.</returns>
        public static InputBoxResult Show( string prompt, string title, string defaultResponse, InputBoxValidatingHandler validator, int xpos, int ypos, bool multiline )
        {
            using ( InputBox form = new InputBox() ) {
                if ( multiline ) {
                    form.textBoxText.Multiline = true;
                    form.textBoxText.Height += 300;
                    form.Height += 300;
                }

                form.labelPrompt.Text = prompt;
                form.Text = title;
                form.textBoxText.Text = defaultResponse;
                if ( xpos >= 0 && ypos >= 0 ) {
                    form.StartPosition = FormStartPosition.Manual;
                    form.Left = xpos;
                    form.Top = ypos;
                }
                form.Validator = validator;

                DialogResult result = form.ShowDialog();

                InputBoxResult retval = new InputBoxResult();
                if ( result == DialogResult.OK ) {
                    retval.Text = form.textBoxText.Text;
                    retval.OK = true;
                }
                return retval;
            }
        }
예제 #8
0
 private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
 {
     if (e.RowIndex > -1 && e.RowIndex < dataGridView1.Rows.Count - 1)
     {
         int.TryParse(dataGridView1.Rows[e.RowIndex].Cells["id"].Value.ToString(), out id);
         string imeColumne = dataGridView1.Columns[e.ColumnIndex].Name;
         if (imeColumne == "obrisi")
         {
             if (PrijavljenJe && PristupJe)
             {
                 InputBox frm = new InputBox();
                 DialogResult rez = frm.ShowDialog();
                 if (rez == DialogResult.OK)
                 {
                     osvjezi = ObrisiMobitel();
                     GetMobiteli();
                 }
             }
         }
         else if (imeColumne == "azuriraj")
         {
             txtImeMobitela.Text = dataGridView1.Rows[e.RowIndex].Cells["ime"].Value.ToString();
             tabControl1.SelectedIndex = 1;
         }
     }
 }
예제 #9
0
        /// <summary>
        /// Load initial game data and assets once.
        /// </summary>
        public override void LoadContent()
        {
            //TODO: Offload to initialize
            ScreenManager.Game.IsMouseVisible = true;
            spriteBatch = ScreenManager.SpriteBatch;
            content = new ContentManager(ScreenManager.Game.Services, "Content");
            //Load banner Image

            //Load Instruction text (also error text)
            textMessage = new TextBox(message,
                new Vector2(this.ScreenManager.GraphicsDevice.Viewport.Width/2, 290), Color.Black);
            textMessage.LoadContent(spriteBatch, ScreenManager.GraphicsDevice,
                content);
            //Load Input box
            inputBox = new InputBox(new Vector2(390, 390), Color.Orange, 10);
            inputBox.LoadContent(spriteBatch, ScreenManager.GraphicsDevice, content);
            //Load Login Button
            loginButton = new Button("Login", new Vector2(390, 500), Color.Aqua);
            loginButton.LoadContent(spriteBatch, ScreenManager.GraphicsDevice,
                content);
            exitButton = new Button("Exit", new Vector2(510, 500), Color.PaleVioletRed);
            exitButton.LoadContent(spriteBatch, ScreenManager.GraphicsDevice,
                content);
            //Load Exit Button
        }
예제 #10
0
        private void archiveMonthToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var input = new InputBox("Enter a Month", "Please enter the month you are archiving"))
            {
                string inputtxt;
                if (input.ShowDialog() == DialogResult.OK)
                    inputtxt = input.InputText.ToUpper();
                else
                    return;

                ReadArchives();
                var exists = _archived.Where(item => String.Compare(item.MonthName.ToUpper(), inputtxt, StringComparison.Ordinal) == 0);

                if (!exists.Any())
                {
                    double projTotal = _projData.Sum();
                    double currTotal = _currData.Sum();
                    _archived.Add(new ArchiveMonth(input.InputText, _projData, projTotal, _listFinances, currTotal));
                    WriteArchives();

                    UIHelper.ClearList(lstItems);
                    _listFinances = new List<FinanceEntry>();
                    _currData = new List<double>();
                    InitProjectionData();
                    Utilities.LoadID(_listFinances);
                    WriteXML();
                    Recalculate();
                    MessageBox.Show("Your total spending for the month left you with: " + (projTotal - currTotal).ToString(Formats.MoneyFormat), "Monthly Total");
                }
                else
                    MessageBox.Show("Error: There is already an entry with the same name","Error");
                _archived = null;
            }
        }
예제 #11
0
        public void Execute(ICSharpCode.TreeView.SharpTreeNode[] selectedNodes)
        {
            //Member
            var member = (IMemberDefinition)((IMemberTreeNode)selectedNodes[0]).Member;
            var rename = GetObjectsToRename(member).ToArray();

            //Content of the input box
            var content = new StackPanel();
            content.Children.Add(new TextBlock() { Inlines = { new Run() { Text = "Insert new name for " }, new Run() { Text = member.Name, FontWeight = System.Windows.FontWeights.Bold }, new Run() { Text = "." } } });
            if (rename.Length > 1)
            {
                content.Children.Add(new TextBlock() { Text = "This action will automatically update the following members:", Margin = new System.Windows.Thickness(0, 3, 0, 0) });
                foreach (var x in rename.Skip(1))
                    content.Children.Add(new TextBlock() { Text = x.Key.Name, FontWeight = System.Windows.FontWeights.Bold, Margin = new System.Windows.Thickness(0, 3, 0, 0) });
            }

            //Asks for the new name and performs the renaming
            var input = new InputBox("New name", content);
            if (input.ShowDialog().GetValueOrDefault(false) && !string.IsNullOrEmpty(input.Value))
            {
                //Performs renaming
                foreach (var x in rename)
                    x.Key.Name = string.Format(x.Value, input.Value);

                //Refreshes the view
                MainWindow.Instance.RefreshDecompiledView();
                selectedNodes[0].Foreground = ILEdit.GlobalContainer.NewNodesBrush;
                MainWindow.Instance.RefreshTreeViewFilter();
            }
        }
 public override void Run()
 {
     IWfBox owner = this.Owner as IWfBox;
     if (owner != null)
     {
         InputBox box2 = new InputBox("请输入使用的远程DAO对象地址:", "提示", "http://127.0.0.1:7502/DBDAO");
         if (box2.ShowDialog(WorkbenchSingleton.MainForm) == DialogResult.OK)
         {
             string result = box2.Result;
             if (!string.IsNullOrEmpty(result))
             {
                 WaitDialogHelper.Show();
                 try
                 {
                     (owner as WfBox).SaveAsProinsts(result);
                 }
                 catch (Exception exception)
                 {
                     MessageHelper.ShowInfo("发生错误:{0}", exception.Message);
                     LoggingService.Error(exception);
                 }
                 finally
                 {
                     WaitDialogHelper.Close();
                 }
             }
         }
     }
 }
예제 #13
0
        /// <summary>
        /// Displays a prompt in a dialog box, waits for the user to input text or click a button.
        /// </summary>
        /// <param name="prompt">String expression displayed as the message in the dialog box</param>
        /// <param name="title">String expression displayed in the title bar of the dialog box</param>
        /// <param name="defaultResponse">String expression displayed in the text box as the default response</param>
        /// <param name="validator">Delegate used to validate the text</param>
        /// <param name="keyPressHandler">Delete used to handle keypress events of the textbox</param>
        /// <param name="xpos">Numeric expression that specifies the distance of the left edge of the dialog box from the left edge of the screen.</param>
        /// <param name="ypos">Numeric expression that specifies the distance of the upper edge of the dialog box from the top of the screen</param>
        /// <returns>An InputBoxResult object with the Text and the OK property set to true when OK was clicked.</returns>
        public static InputBoxResult Show(string prompt, string title, string defaultResponse, InputBoxValidatingHandler validator, KeyPressEventHandler keyPressHandler, int xpos, int ypos)
        {
            using (InputBox form = new InputBox())
            {
                form.label.Text = prompt;
                form.Text = title;
                form.textBox.Text = defaultResponse;
                if (xpos >= 0 && ypos >= 0)
                {
                    form.StartPosition = FormStartPosition.Manual;
                    form.Left = xpos;
                    form.Top = ypos;
                }

                form.Validator = validator;
                form.KeyPressed = keyPressHandler;

                DialogResult result = form.ShowDialog();

                InputBoxResult retval = new InputBoxResult();
                if (result == DialogResult.OK)
                {
                    retval.Text = form.textBox.Text;
                    retval.OK = true;
                }

                return retval;
            }
        }
예제 #14
0
        private void AddButton_Click(object sender, EventArgs e)
        {
            var input = new InputBox("请输入一个名字:", "新增操作者", "");
            var result = input.ShowDialog(this);
            if (result == DialogResult.OK)
            {
                var name = input.InputResult.Trim();
                bool nameExists = false;
                foreach (string n in OperatorsListBox.Items) {
                    if (n == name)
                    {
                        nameExists = true;
                        break;
                    }
                }

                if (!nameExists)
                {
                    var db = new DataProcess();
                    db.addOperator(name);
                    OperatorsListBox.Items.Add(name);
                }
                else
                {
                    MessageBox.Show(this, "名字已存在,请勿重复添加。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
        }
 public override void Run()
 {
     if (this.IsEnabled && (MessageHelper.ShowYesNoInfo("你真的要更新数据库缓存版本吗,这将会使客户端重新更新整个缓存数据") == DialogResult.Yes))
     {
         InputBox box = new InputBox("请输入使用的远程DAO对象地址,\r\n如果取消将更新当前服务器。", "提示:", "http://127.0.0.1:7502/DBDAO");
         string result = string.Empty;
         if (box.ShowDialog(WorkbenchSingleton.MainForm) == DialogResult.OK)
         {
             result = box.Result;
             if (string.IsNullOrEmpty(result))
             {
                 MessageHelper.ShowInfo("没有输入远程DAO对象地址");
                 return;
             }
         }
         try
         {
             DBSessionFactory.GetInstanceByUrl(result).UpdateVersion();
             MessageHelper.ShowInfo("更新数据库缓存版本成功!");
         }
         catch (Exception exception)
         {
             MessageHelper.ShowError("更新数据库缓存时发生错误", exception);
             LoggingService.Error(exception);
         }
     }
 }
 public override void Run()
 {
     if (this.IsEnabled)
     {
         InputBox box = new InputBox("请输入使用的远程服务自动升级对象地址:", "提示:", "http://127.0.0.1:7502/RemoteUpdate");
         string result = string.Empty;
         if (box.ShowDialog(WorkbenchSingleton.MainForm) == DialogResult.OK)
         {
             result = box.Result;
             if (string.IsNullOrEmpty(result))
             {
                 MessageHelper.ShowInfo("没有输入远程对象地址");
             }
             else
             {
                 try
                 {
                     string remoteLog = (Activator.GetObject(typeof(IRemoteUpdate), result) as IRemoteUpdate).GetRemoteLog();
                     string path = Path.GetTempFileName() + ".txt";
                     File.WriteAllText(path, remoteLog);
                     Process.Start(path);
                 }
                 catch (Exception exception)
                 {
                     MessageHelper.ShowError("远程服务执行升级操作发生错误", exception);
                     LoggingService.Error(exception);
                 }
             }
         }
     }
 }
예제 #17
0
 public static string Show(string inputBoxText)
 {
     newInputBox = new InputBox();
     newInputBox.label1.Text = inputBoxText;
     newInputBox.ShowDialog();
     return newInputBox.textBox1.Text;
 }
예제 #18
0
 public static DialogResult Show(string title, string prompt, out string result)
 {
     InputBox input = new InputBox(title, prompt);
     DialogResult retval = input.ShowDialog();
     result = input.textInput.Text;
     return retval;
 }
예제 #19
0
        /* Brings up the Input Box with the arguments of a */
        public Form1.IBArg[] CallIBox(Form1.IBArg[] a)
        {
            InputBox ib = new InputBox();

            ib.Arg = a;
            ib.fmHeight = this.Height;
            ib.fmWidth = this.Width;
            ib.fmLeft = this.Left;
            ib.fmTop = this.Top;
            ib.TopMost = true;
            ib.BackColor = Form1.ncBackColor;
            ib.ForeColor = Form1.ncForeColor;
            ib.Show();

            while (ib.ret == 0)
            {
                a = ib.Arg;
                Application.DoEvents();
            }
            a = ib.Arg;

            if (ib.ret == 1)
                return a;
            else if (ib.ret == 2)
                return null;

            return null;
        }
예제 #20
0
		private void butAdd_Click(object sender,EventArgs e) {
			if(!Security.IsAuthorized(Permissions.WikiListSetup)) {
				return;
			}
			InputBox inputListName = new InputBox("New List Name");
			inputListName.ShowDialog();
			if(inputListName.DialogResult!=DialogResult.OK) {
				return;
			}
			//Format input as it would be saved in the database--------------------------------------------
			inputListName.textResult.Text=inputListName.textResult.Text.ToLower().Replace(" ","");
			//Validate list name---------------------------------------------------------------------------
			if(DbHelper.isMySQLReservedWord(inputListName.textResult.Text)) {
				//Can become an issue when retrieving column header names.
				MsgBox.Show(this,"List name is a reserved word in MySQL.");
				return;
			}
			if(inputListName.textResult.Text=="") {
				MsgBox.Show(this,"List name cannot be blank.");
				return;
			}
			if(WikiLists.CheckExists(inputListName.textResult.Text)) {
				if(!MsgBox.Show(this,MsgBoxButtons.YesNo,"List already exists with that name. Would you like to edit existing list?")) {
					return;
				}
			}
			FormWikiListEdit FormWLE = new FormWikiListEdit();
			FormWLE.WikiListCurName = inputListName.textResult.Text;
			//FormWLE.IsNew=true;//set within the form.
			FormWLE.ShowDialog();
			FillList();
		}
예제 #21
0
        private void SomeSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            const int REGISTERASISTENCE = 1;
            const int GOASSISTENCESS = 2;
            var comboBox = sender as ComboBox;
            int index = (int)comboBox.SelectedValue;
            var selectedItem = this.dgMeetings.CurrentItem;
            MeetingModel meeting = (MeetingModel)selectedItem;

            switch (index)
            {
                case REGISTERASISTENCE: {
                    var dialog = new InputBox();
                    if (dialog.ShowDialog() == true)
                    {
                        MessageBox.Show("You said: " + dialog.ResponseText + "MEETING ID " + meeting.ID);
                        MainWindow.instance.UseAsisstControlPanel(Convert.ToInt32(dialog.ResponseText), meeting.ID);
                    }
                    
                    
                    break;
                }
                case GOASSISTENCESS:{
                    MainWindow.instance.UseAsisstReportPanel(meeting.ID);

                break;
                }

            }
           

        }
예제 #22
0
 /// <summary>
 /// Prompts the user for an input string
 /// </summary>
 /// <param name="owner">The window requesting the input string</param>
 /// <param name="prompt">Prompt to display in the input window</param>
 /// <param name="caption">Caption to use as the title of the input window</param>
 /// <param name="defaultValue">Default input value</param>
 /// <returns>User-input string</returns>
 public static string Read(IWin32Window owner, string prompt, string caption, string defaultValue) {
   InputBox ib = new InputBox(caption, prompt, defaultValue);
   ib.ShowDialog(owner);
   if(ib.DialogResult == DialogResult.OK)
     return ib._txtValue.Text;
   else
     return defaultValue;
 }
예제 #23
0
 public static string Show(string title, string text)
 {
     InputBox ib = new InputBox();
     ib.Text = title;
     ib.label1.Text = text;
     ib.ShowDialog();
     return ib.Result;
 }
예제 #24
0
 public static string Show(Form parent, string message, string defaultValue)
 {
     InputBox ib = new InputBox(message);
     ib.text.Text = defaultValue;
     DialogResult dr = ib.ShowDialog(parent);
     if (dr == DialogResult.Cancel) return null;
     else return ib.text.Text;
 }
예제 #25
0
파일: InputBox.cs 프로젝트: erbuka/andrea
 public static InputBoxResult Prompt(string title)
 {
     InputBox ibf = new InputBox();
     InputBoxResult result = new InputBoxResult();
     result.Result = ibf.ShowDialog();
     result.Value = ibf.txtInputText.Text;
     return result;
 }
예제 #26
0
 public void mapFinished()
 {
     levelModel.LevelStarted = false;
     InputBox test = new InputBox(this);
     test.VerticalAlignment = VerticalAlignment.Center;
     test.HorizontalAlignment = HorizontalAlignment.Center;
     gameGrid.Children.Add(test);
 }
예제 #27
0
 internal static bool PasteContentData(InputBox inputBox, IDataObject iDataObject)
 {
     TextData data = TryGetText(iDataObject);
     if (!data.ContainsData)
     {
         if (iDataObject.GetDataPresent(DataFormats.Bitmap, true))
         {
             inputBox.Paste(iDataObject);
             return true;
         }
         return false;
     }
     inputBox.TempFlowDocument.Blocks.Clear();
     TextRange range = null;
     if (data.Format == BamaDataFormat)
     {
         object obj2 = XamlReader.Parse(data.Data);
         if (obj2 is Block)
         {
             inputBox.TempFlowDocument.Blocks.Add(obj2 as Block);
         }
         else if (obj2 is Inline)
         {
             Span span = new Span(inputBox.TempFlowDocument.ContentStart, inputBox.TempFlowDocument.ContentEnd)
             {
                 Inlines = { obj2 as Span }
             };
         }
         range = new TextRange(inputBox.TempFlowDocument.ContentStart, inputBox.TempFlowDocument.ContentEnd);
         range.ClearAllProperties();
         inputBox.Selection.Text = "";
         Span newspan = new Span(inputBox.Selection.Start, inputBox.Selection.End);
         ReplaceControls.AddBlocksToSpan(inputBox.TempFlowDocument, newspan);
         inputBox.CaretPosition = newspan.ElementEnd.GetInsertionPosition(LogicalDirection.Forward);
     }
     else
     {
         range = new TextRange(inputBox.TempFlowDocument.ContentStart, inputBox.TempFlowDocument.ContentEnd);
         using (MemoryStream stream = new MemoryStream())
         {
             using (StreamWriter writer = new StreamWriter(stream))
             {
                 writer.Write(data.Data);
                 writer.Flush();
                 stream.Position = 0L;
                 range.Load(stream, data.Format);
             }
         }
         range.ClearAllProperties();
         inputBox.Selection.Text = "";
         Span span3 = new Span(inputBox.Selection.Start, inputBox.Selection.End);
         ReplaceControls.AddBlocksToSpan(inputBox.TempFlowDocument, span3);
         inputBox.CaretPosition = span3.ElementEnd.GetInsertionPosition(LogicalDirection.Forward);
     }
     inputBox.TempFlowDocument.Blocks.Clear();
     return true;
 }
예제 #28
0
 public static string Get(string caption, string label)
 {
     InputBox dlg = new InputBox();
     dlg.Text = caption;
     dlg.label1.Text = label;
     if (dlg.ShowDialog() == DialogResult.OK)
         return dlg.textBox1.Text;
     return "";
 }
예제 #29
0
        public static String Show(String title)
        {
            val = "";
            InputBox ib = new InputBox();
            ib.Text = title;
            ib.ShowDialog();

            return val;
        }
예제 #30
0
 private void Window_Activated(object sender, EventArgs e)
 {
     InputBox.Focus();
 }
예제 #31
0
        public FavoriteConfigurationElementCollection ImportFavorites(string Filename)
        {
            FavoriteConfigurationElementCollection fav = null;
            InputBoxResult result = InputBox.Show("Password", "vRD Password", '*');

            if (result.ReturnCode == System.Windows.Forms.DialogResult.OK)
            {
                byte[] file = System.IO.File.ReadAllBytes(Filename);
                string xml  = ImportvRD.a(file, result.Text).Replace(" encoding=\"utf-16\"", "");
                byte[] data = System.Text.ASCIIEncoding.Default.GetBytes(xml);
                using (System.IO.MemoryStream sw = new MemoryStream(data)) {
                    if (sw.Position > 0 & sw.CanSeek)
                    {
                        sw.Seek(0, SeekOrigin.Begin);
                    }
                    System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(vRdImport.vRDConfigurationFile));
                    object results = x.Deserialize(sw);

                    List <vRdImport.Connection> connections = new List <vRdImport.Connection>();
                    List <vRdImport.vRDConfigurationFileConnectionsFolder> folders = new List <vRdImport.vRDConfigurationFileConnectionsFolder>();
                    Dictionary <string, vRdImport.vRDConfigurationFileCredentialsFolderCredentials> credentials = new Dictionary <string, vRdImport.vRDConfigurationFileCredentialsFolderCredentials>();

                    if (results != null)
                    {
                        vRdImport.vRDConfigurationFile config = (results as vRdImport.vRDConfigurationFile);
                        if (config != null)
                        {
                            //scan in all credentials into a dictionary
                            foreach (object item in config.Items)
                            {
                                if (item is vRdImport.vRDConfigurationFileCredentialsFolder)
                                {
                                    vRdImport.vRDConfigurationFileCredentialsFolder credentialFolder = (item as vRdImport.vRDConfigurationFileCredentialsFolder);
                                    if (credentialFolder != null)
                                    {
                                        foreach (vRdImport.vRDConfigurationFileCredentialsFolderCredentials cred in credentialFolder.Credentials)
                                        {
                                            credentials.Add(cred.Guid, cred);
                                        }
                                    }
                                }
                                if (item is vRdImport.vRDConfigurationFileCredentialsFolderCredentials)
                                {
                                    vRdImport.vRDConfigurationFileCredentialsFolderCredentials cred = (item as vRdImport.vRDConfigurationFileCredentialsFolderCredentials);
                                    credentials.Add(cred.Guid, cred);
                                }
                            }

                            //scan in the connections, and recurse folders
                            foreach (object item in config.Items)
                            {
                                if (item is vRdImport.Connection)
                                {
                                    vRdImport.Connection connection = (item as vRdImport.Connection);
                                    if (connection != null)
                                    {
                                        connections.Add(connection);
                                    }
                                }
                                else if (item is vRdImport.vRDConfigurationFileConnectionsFolder)
                                {
                                    vRdImport.vRDConfigurationFileConnectionsFolder folder = (item as vRdImport.vRDConfigurationFileConnectionsFolder);
                                    if (folder != null)
                                    {
                                        folders.Add(folder);
                                    }
                                }
                            }
                        }
                    }
                    string f = "";
                }
            }

            return(fav);
        }
예제 #32
0
 protected void Page_Load(object sender, EventArgs e)
 {
     InputBox.Focus();
 }
예제 #33
0
파일: BuyAgent.cs 프로젝트: 9iks/Razor-1
        public override void OnButtonPress(int num)
        {
            switch (num)
            {
            case 1:
                World.Player.SendMessage(MsgLevel.Force, LocString.TargItemAdd);
                Targeting.OneTimeTarget(new Targeting.TargetResponseCallback(OnTarget));
                break;

            case 2:
                if (m_SubList == null)
                {
                    break;
                }

                if (m_SubList.SelectedIndex >= 0)
                {
                    BuyEntry e      = (BuyEntry)m_Items[m_SubList.SelectedIndex];
                    ushort   amount = e.Amount;
                    if (InputBox.Show(Engine.MainWindow, Language.GetString(LocString.EnterAmount),
                                      Language.GetString(LocString.InputReq), amount.ToString()))
                    {
                        e.Amount = (ushort)InputBox.GetInt(1);
                        m_SubList.BeginUpdate();
                        m_SubList.Items.Clear();
                        for (int i = 0; i < m_Items.Count; i++)
                        {
                            m_SubList.Items.Add(m_Items[i]);
                        }

                        m_SubList.EndUpdate();
                    }
                }

                break;

            case 3:

                if (MessageBox.Show(Language.GetString(LocString.Confirm), Language.GetString(LocString.ClearList),
                                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (m_SubList.SelectedIndex >= 0)
                    {
                        m_Items.RemoveAt(m_SubList.SelectedIndex);
                        m_SubList.Items.RemoveAt(m_SubList.SelectedIndex);
                        m_SubList.SelectedIndex = -1;
                    }
                }

                break;

            case 4:

                if (MessageBox.Show(Language.GetString(LocString.Confirm), Language.GetString(LocString.ClearList),
                                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    m_SubList.Items.Clear();
                    m_Items.Clear();
                }

                break;

            case 5:
                m_Enabled        = !m_Enabled;
                m_EnableBTN.Text = Language.GetString(m_Enabled ? LocString.PushDisable : LocString.PushEnable);
                break;
            }
        }
예제 #34
0
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.Text == "Not in The List")
            {
                string inputParticulars = null;
                //var inputBox = InputBox;
                InputBox.Show("Please Input Particular", "Inpute Here", ref inputParticulars);
                if (string.IsNullOrWhiteSpace(inputParticulars))
                {
                    comboBox1.SelectedIndex = -1;
                }
                else
                {
                    con = new SqlConnection(cs.DBConn);
                    con.Open();
                    string q23 = "select ParticularName from ParticularTable where ParticularName = '" + inputParticulars + "' ";
                    cmd = new SqlCommand(q23, con);
                    rdr = cmd.ExecuteReader();
                    if (rdr.Read() && !rdr.IsDBNull(0))
                    {
                        MessageBox.Show("This Particular Already Exists,Please Select From List", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        con.Close();
                        comboBox1.SelectedIndex = -1;
                    }
                    else
                    {
                        try
                        {
                            con = new SqlConnection(cs.DBConn);
                            con.Open();
                            string q32 = "insert into ParticularTable (ParticularName) values (@d1)" + "SELECT CONVERT(int, SCOPE_IDENTITY())";
                            cmd = new SqlCommand(q32, con);
                            cmd.Parameters.AddWithValue("@d1", inputParticulars);
                            cmd.ExecuteNonQuery();
                            con.Close();
                            comboBox1.Items.Clear();
                            getParticlrs();
                            comboBox1.SelectedText = inputParticulars;
                        }
                        catch (Exception exception)
                        {
                            MessageBox.Show(exception.Message, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            else
            {
                try
                {
                    con = new SqlConnection(cs.DBConn);
                    con.Open();
                    string q4 = "select ParticularName from ParticularTable where ParticularName = '" + comboBox1.Text + "' ";
                    cmd = new SqlCommand(q4, con);
                    rdr = cmd.ExecuteReader();

                    if (rdr.Read())
                    {
                        particularsTextBox.Text = rdr.GetString(0);
                    }
                    con.Close();
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
예제 #35
0
        private void bb_alterar_Click(object sender, EventArgs e)
        {
            if (bsItensExpedicao.Current != null)
            {
                string pLogin = Utils.Parametros.pubLogin;
                if (!st_alterarserie)
                {
                    using (Parametros.Diversos.TFRegraUsuario fRegra = new Parametros.Diversos.TFRegraUsuario())
                    {
                        fRegra.Ds_regraespecial = "PERMITIR ALTERAR Nº SÉRIE";
                        fRegra.Login            = Utils.Parametros.pubLogin;
                        if (fRegra.ShowDialog() == DialogResult.OK)
                        {
                            st_alterarserie = true;
                            pLogin          = fRegra.Login;
                        }
                    }
                }
                if (st_alterarserie)
                {
                    if (string.IsNullOrEmpty((bsItensExpedicao.Current as TRegistro_ItensExpedicao).Nr_serie))
                    {
                        MessageBox.Show("Item não possui Nº Série para ser alterado!", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    string vParam = "(|NOT EXISTS|(SELECT 1 FROM TB_FAT_ItensExpedicao x " +
                                    "where a.id_serie = x.id_serie ) " +
                                    "or exists (SELECT 1 FROM TB_FAT_ItensExpedicao x " +
                                    "inner join TB_FAT_Ordem_X_Expedicao y " +
                                    "on x.CD_Empresa = y.CD_Empresa " +
                                    "and x.ID_Expedicao = y.id_expedicao " +
                                    "inner join TB_FAT_CompDevol_NF w " +
                                    "on y.CD_Empresa = w.CD_Empresa " +
                                    "and y.Nr_lanctoFiscal = w.Nr_LanctoFiscal_Origem " +
                                    "inner join TB_PRD_Seriedevolvida z " +
                                    "on w.cd_empresa = z.cd_empresa " +
                                    "and w.nr_lanctofiscal_destino = z.nr_lanctofiscal " +
                                    "and w.id_nfitem_destino = z.ID_NFItem " +
                                    "where a.id_serie = x.id_serie )); " +
                                    "a.cd_empresa|=|'" + (bsItensExpedicao.Current as CamadaDados.Faturamento.Pedido.TRegistro_ItensExpedicao).Cd_empresa.Trim() + "';" +
                                    "a.cd_produto|=|'" + (bsItensExpedicao.Current as CamadaDados.Faturamento.Pedido.TRegistro_ItensExpedicao).Cd_produto.Trim() + "';" +
                                    "isnull(a.st_registro, 'P')|=|'P'";
                    Componentes.EditDefault id = new Componentes.EditDefault();
                    id.NM_CampoBusca = "ID_Serie";
                    Componentes.EditDefault ds = new Componentes.EditDefault();
                    ds.NM_CampoBusca = "Nr_serie";
                    FormBusca.UtilPesquisa.BTN_BUSCA("a.Nr_serie|Nº Série|200;" +
                                                     "a.Id_serie|ID|50",
                                                     new Componentes.EditDefault[] { id, ds },
                                                     new CamadaDados.Producao.Producao.TCD_SerieProduto(),
                                                     vParam);

                    if (!string.IsNullOrEmpty(id.Text))
                    {
                        try
                        {
                            InputBox ibp = new InputBox();
                            ibp.Text = "Motivo Cancelamento Locação";
                            string motivo = ibp.ShowDialog();
                            if (string.IsNullOrEmpty(motivo))
                            {
                                MessageBox.Show("Obrigatorio informar motivo de cancelamento da locação!", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                return;
                            }
                            if (motivo.Trim().Length < 10)
                            {
                                MessageBox.Show("Motivo de cancelamento deve ter mais que 10 caracteres!", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                return;
                            }
                            CamadaNegocio.Faturamento.Pedido.TCN_TrocaSerieExped.Gravar(
                                new TRegistro_TrocaSerieExped()
                            {
                                Cd_empresa      = (bsItensExpedicao.Current as CamadaDados.Faturamento.Pedido.TRegistro_ItensExpedicao).Cd_empresa,
                                Id_expedicaostr = (bsItensExpedicao.Current as CamadaDados.Faturamento.Pedido.TRegistro_ItensExpedicao).Id_expedicaostr,
                                Id_itemstr      = (bsItensExpedicao.Current as CamadaDados.Faturamento.Pedido.TRegistro_ItensExpedicao).Id_itemstr,
                                Id_SerieNewstr  = id.Text,
                                Id_SerieOldstr  = (bsItensExpedicao.Current as CamadaDados.Faturamento.Pedido.TRegistro_ItensExpedicao).Id_seriestr,
                                Login           = pLogin,
                                Motivo          = motivo
                            }, null);
                            MessageBox.Show("Nº Série alterado com sucesso!", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            bsExpedicao_PositionChanged(this, new EventArgs());
                        }
                        catch (Exception ex)
                        { MessageBox.Show(ex.Message.Trim(), "Erro", MessageBoxButtons.OK, MessageBoxIcon.Information); }
                    }
                }
            }
        }
예제 #36
0
        static void Main(string[] args)
        {
            string file       = "";
            string exportPath = "";
            string user       = Settings.Default.DefaultUser;
            string password   = Settings.Default.DefaultPassword;


            Project prj = null;

            if (args.Count() < 1)
            {
                Application app = new Application();
                var         ask = new AskOpen();
                app.Run(ask);
                var res = ask.Result;
                resetSetpoints     = ask.chkResetSetpoints.IsChecked == true;
                removeCodeFromXml  = ask.chkRemoveCode.IsChecked == true;
                removeAllBlanks    = ask.rbRemoveAllBlanks.IsChecked == true;
                removeOnlyOneBlank = ask.rbRemoveOnlyOneBlank.IsChecked == true;
                removeNoBlanks     = ask.rbRemoveNoBlanks.IsChecked == true;

                if (object.Equals(res, false))
                {
                    OpenFileDialog op = new OpenFileDialog();
                    op.Filter          = "TIA-Portal Project|*.ap13;*.ap14;*.ap15;*.ap15_1";
                    op.CheckFileExists = false;
                    op.ValidateNames   = false;
                    var ret = op.ShowDialog();
                    if (ret == true)
                    {
                        file = op.FileName;
                    }
                    else
                    {
                        Console.WriteLine("Bitte S7 projekt als Parameter angeben!");
                        return;
                    }

                    if (Path.GetExtension(file) == ".ap15_1")
                    {
                        if (InputBox.Show("Credentials", "Enter Username (or cancel if not used)", ref user) !=
                            DialogResult.Cancel)
                        {
                            if (InputBox.Show("Credentials", "Enter Password", ref password) != DialogResult.Cancel)
                            {
                            }
                            else
                            {
                                user     = "";
                                password = "";
                            }
                        }
                        else
                        {
                            user     = "";
                            password = "";
                        }
                    }

                    exportPath = Path.GetDirectoryName(file);
                    exportPath = Path.GetFullPath(Path.Combine(exportPath, "..\\Export"));
                }
                else if (res != null)
                {
                    var ver = ask.Result as string;
                    prj = Projects.AttachProject(ver);

                    exportPath = Path.GetDirectoryName(prj.ProjectFile);
                    exportPath = Path.GetFullPath(Path.Combine(exportPath, "..\\Export"));
                }
                else
                {
                    Environment.Exit(0);
                }

                if (Directory.Exists(exportPath))
                {
                    if (
                        MessageBox.Show(exportPath + " wird gelöscht. Möchten Sie fortfahren?",
                                        "Sicherheitsabfrage",
                                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        DeleteDirectory(exportPath);
                    }
                    else
                    {
                        Environment.Exit(-1);
                    }
                }

                Directory.CreateDirectory(exportPath);
            }
            else
            {
                file = args[0];
                if (args.Length > 1)
                {
                    user = args[1];
                }
                if (args.Length > 2)
                {
                    password = args[2];
                }
            }

            if (prj == null)
            {
                Credentials credentials = null;
                if (!string.IsNullOrEmpty(user) && !string.IsNullOrEmpty(password))
                {
                    credentials = new Credentials()
                    {
                        Username = user, Password = new SecureString()
                    };
                    foreach (char c in password)
                    {
                        credentials.Password.AppendChar(c);
                    }
                }

                prj = Projects.LoadProject(file, false, credentials);
            }

            _projectType = prj.ProjectType;

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Opened Project - " + prj.ProjectType.ToString());
            Console.WriteLine("Exporting to Folder: " + exportPath);
            Console.WriteLine();
            List <string> skippedBlocksList = new List <string>();

            ParseFolder(prj.ProjectStructure, exportPath, skippedBlocksList);

            Console.WriteLine();
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Red;
            skippedBlocksList.ForEach(i => Console.WriteLine("{0}", i));
            Console.WriteLine();
            Console.WriteLine(skippedBlocksList.Count() + " blocks were skipped");
            Console.ReadKey();
        }
예제 #37
0
        private void BUT_connect_Click(object sender, EventArgs e)
        {
            if (comPort.IsOpen)
            {
                threadrun = false;
                comPort.Close();
                BUT_connect.Text = Strings.Connect;
            }
            else
            {
                try
                {
                    comPort.PortName = CMB_serialport.Text;
                }
                catch
                {
                    CustomMessageBox.Show(Strings.InvalidPortName, Strings.ERROR);
                    return;
                }
                try
                {
                    comPort.BaudRate = int.Parse(CMB_baudrate.Text);
                }
                catch
                {
                    CustomMessageBox.Show(Strings.InvalidBaudRate, Strings.ERROR);
                    return;
                }
                try
                {
                    comPort.Open();
                }
                catch (Exception ex)
                {
                    CustomMessageBox.Show(Strings.ErrorConnecting + "\n" + ex.ToString(), Strings.ERROR);
                    return;
                }


                string alt = "100";

                if (MainV2.comPort.MAV.cs.firmware == Firmwares.ArduCopter2)
                {
                    alt = (10 * CurrentState.multiplierdist).ToString("0");
                }
                else
                {
                    alt = (100 * CurrentState.multiplierdist).ToString("0");
                }
                if (DialogResult.Cancel == InputBox.Show("Enter Alt", "Enter Alt (relative to home alt)", ref alt))
                {
                    return;
                }

                intalt = (int)(100 * CurrentState.multiplierdist);
                if (!int.TryParse(alt, out intalt))
                {
                    CustomMessageBox.Show(Strings.InvalidAlt, Strings.ERROR);
                    return;
                }

                intalt = (int)(intalt / CurrentState.multiplierdist);

                t12 = new System.Threading.Thread(new System.Threading.ThreadStart(mainloop))
                {
                    IsBackground = true,
                    Name         = "followme Input"
                };
                t12.Start();

                BUT_connect.Text = Strings.Stop;
            }
        }
예제 #38
0
        public override void OnButtonPress(int num)
        {
            ConfigItem item = listBox.SelectedItem as ConfigItem;

            if (item == null)
            {
                return;
            }
            if (item.Value is string)
            {
                if (InputBox.Show("Input string") && !string.IsNullOrEmpty(InputBox.GetString()))
                {
                    item.Value = InputBox.GetString();
                }
            }
            else if (item.Value is bool)
            {
                item.Value = !(bool)item.Value;
            }
            else if (item.Value is uint)
            {
                Targeting.OneTimeTarget((l, s, p, g) =>
                {
                    item.Value = s == World.Player.Serial ? 0 : s.Value;
                    listBox.Items[listBox.SelectedIndex] = item;
                });
            }
            else if (item.Value is byte)
            {
                if (InputBox.Show("Input value") && (InputBox.GetInt(-1) >= 0 || InputBox.GetInt(-1) <= 100))
                {
                    item.Value = (byte)InputBox.GetInt(-1);
                }
            }
            else if (item.Value is ushort)
            {
                HueEntry hueEntry = new HueEntry((ushort)item.Value);
                if (hueEntry.ShowDialog(Engine.MainWindow) == DialogResult.OK)
                {
                    item.Value = (ushort)hueEntry.Hue;
                }
            }
            else if (item.Value.GetType().IsEnum)
            {
                Type type  = item.Value.GetType();
                int  value = (int)item.Value;
                while (!Enum.IsDefined(type, ++value))
                {
                    if (value >= Enum.GetValues(type).Length)
                    {
                        value = -1;
                    }
                }
                item.Value = Enum.ToObject(type, value);
            }
            else
            {
                throw new NotImplementedException();
            }
            listBox.Items[listBox.SelectedIndex] = item;
        }
        static void Main(string[] args)
        {
            string file       = "";
            string exportPath = "";
            string user       = Settings.Default.DefaultUser;
            string password   = Settings.Default.DefaultPassword;

            if (args.Count() < 1)
            {
                OpenFileDialog op = new OpenFileDialog();
                op.Filter          = "TIA-Portal Project|*.ap13;*.ap14;*.ap15;*.ap15_1";
                op.CheckFileExists = false;
                op.ValidateNames   = false;
                var ret = op.ShowDialog();
                if (ret == DialogResult.OK)
                {
                    file = op.FileName;
                }
                else
                {
                    Console.WriteLine("Bitte S7 projekt als Parameter angeben!");
                    return;
                }

                if (Path.GetExtension(file) == ".ap15_1")
                {
                    if (InputBox.Show("Credentials", "Enter Username (or cancel if not used)", ref user) != DialogResult.Cancel)
                    {
                        if (InputBox.Show("Credentials", "Enter Password", ref password) != DialogResult.Cancel)
                        {
                        }
                        else
                        {
                            user     = "";
                            password = "";
                        }
                    }
                    else
                    {
                        user     = "";
                        password = "";
                    }
                }

                exportPath = Path.GetDirectoryName(file);
                exportPath = Path.GetFullPath(Path.Combine(exportPath, "..\\Export"));
                if (Directory.Exists(exportPath))
                {
                    if (
                        MessageBox.Show(exportPath + " wird gelöscht. Möchten Sie fortfahren?", "Sicherheitsabfrage",
                                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        Directory.Delete(exportPath, true);
                    }
                    else
                    {
                        Environment.Exit(-1);
                    }
                }
                Directory.CreateDirectory(exportPath);
            }
            else
            {
                file = args[0];
                if (args.Length > 1)
                {
                    user = args[1];
                }
                if (args.Length > 2)
                {
                    password = args[2];
                }
            }

            Credentials credentials = null;

            if (!string.IsNullOrEmpty(user) && !string.IsNullOrEmpty(password))
            {
                credentials = new Credentials()
                {
                    Username = user, Password = new SecureString()
                };
                foreach (char c in password)
                {
                    credentials.Password.AppendChar(c);
                }
            }
            var prj = Projects.LoadProject(file, false, credentials);

            List <string> skippedBlocksList = new List <string>();

            ParseFolder(prj.ProjectStructure, exportPath, skippedBlocksList);

            Console.WriteLine();
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Red;
            skippedBlocksList.ForEach(i => Console.WriteLine("{0}", i));
            Console.WriteLine();
            Console.WriteLine(skippedBlocksList.Count() + " blocks were skipped");
            Console.ReadKey();
        }
예제 #40
0
        private void FillRecords()
        {
            pnl.Visible = false;
            pnl.Controls.Clear();

            var unitHeight  = (new TextBox()
            {
                Font = this.Font
            }).Height;
            var labelWidth  = pnl.ClientSize.Width / 4;
            var labelBuffer = SystemInformation.VerticalScrollBarWidth + 1;

            var     y = 0;
            TextBox titleTextBox;
            {
                var record = this.Item[RecordType.Title];
                titleTextBox = new TextBox()
                {
                    Font = this.Font, Location = new Point(labelWidth + labelBuffer, 0), Tag = record, Text = record.ToString(), Width = pnl.ClientSize.Width - labelWidth - labelBuffer, ReadOnly = !this.Editable, Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right
                };
                titleTextBox.GotFocus    += (object sender2, EventArgs e2) => { ((TextBox)sender2).SelectAll(); };
                titleTextBox.TextChanged += (object sender2, EventArgs e2) => { btnOK.Enabled = (((Control)sender2).Text.Trim().Length > 0); };
                pnl.Controls.Add(titleTextBox);
                var label = new Label()
                {
                    AutoEllipsis = true, Location = new Point(0, y), Size = new Size(labelWidth, unitHeight), Text = "Name:", TextAlign = ContentAlignment.MiddleLeft, UseMnemonic = false
                };
                pnl.Controls.Add(label);

                y += titleTextBox.Height + (label.Height / 4);
            }

            ComboBox categoryComboBox;

            {
                var record = this.Item[RecordType.Group];
                categoryComboBox = new ComboBox()
                {
                    Font = this.Font, Location = new Point(labelWidth + labelBuffer, y), Tag = record, Text = record.ToString(), Width = pnl.ClientSize.Width - labelWidth - labelBuffer, Enabled = this.Editable, Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right
                };
                categoryComboBox.GotFocus += (object sender2, EventArgs e2) => { ((ComboBox)sender2).SelectAll(); };
                foreach (var category in this.Categories)
                {
                    categoryComboBox.Items.Add(category);
                }
                if (this.DefaultCategory != null)
                {
                    categoryComboBox.Text = this.DefaultCategory;
                }
                pnl.Controls.Add(categoryComboBox);
                var label = new Label()
                {
                    AutoEllipsis = true, Location = new Point(0, y), Size = new Size(labelWidth, unitHeight), Text = "Category:", TextAlign = ContentAlignment.MiddleLeft, UseMnemonic = false
                };
                pnl.Controls.Add(label);

                if (!string.IsNullOrEmpty(record.Text))
                {
                    var renameButton = NewCustomCommandButton(categoryComboBox, delegate {
                        using (var frm = new InputBox($"Rename all categories named \"{record.Text}\" to:", categoryComboBox.Text)) {
                            if (frm.ShowDialog(this) == DialogResult.OK)
                            {
                                var groupFrom = this.Item.Group;
                                var groupTo   = frm.Text;
                                foreach (var entry in this.Document.Entries)
                                {
                                    if (string.Equals(groupFrom, entry.Group, StringComparison.CurrentCultureIgnoreCase))
                                    {
                                        entry.Group = groupTo;
                                    }
                                }
                                categoryComboBox.Text = groupTo;
                            }
                        }
                    }, "Rename group", "btnGroupRename");
                    pnl.Controls.Add(renameButton);
                    renameButton.Enabled = categoryComboBox.Enabled;

                    btnEdit.Click += delegate {
                        renameButton.Enabled = categoryComboBox.Enabled;
                    };
                }

                y += titleTextBox.Height + (label.Height / 4);
            }

            y += unitHeight / 2;

            int yH;

            foreach (var record in this.Item.Records)
            {
                var label = new Label()
                {
                    AutoEllipsis = true, Location = new Point(0, y), Size = new Size(labelWidth, unitHeight), Text = Helpers.GetRecordCaption(record) + ":", TextAlign = ContentAlignment.MiddleLeft, UseMnemonic = false
                };

                switch (record.RecordType)
                {
                case RecordType.Uuid:
                case RecordType.Group:
                case RecordType.Title:
                case RecordType.CreationTime:
                case RecordType.LastAccessTime:
                case RecordType.LastModificationTime:
                case RecordType.PasswordExpiryTime:
                case RecordType.PasswordModificationTime:
                case RecordType.PasswordHistory:
                case RecordType.Autotype:
                    continue;

                case RecordType.UserName:
                case RecordType.CreditCardExpiration: {
                    var textBox = NewTextBox(labelWidth, y, record);
                    pnl.Controls.Add(textBox);

                    pnl.Controls.Add(NewCopyButton(textBox, record.RecordType));

                    yH = textBox.Height;
                }
                break;

                case RecordType.CreditCardVerificationValue:
                case RecordType.CreditCardPin: {
                    var textBox = NewTextBox(labelWidth, y, record);
                    textBox.UseSystemPasswordChar = true;
                    pnl.Controls.Add(textBox);

                    pnl.Controls.Add(NewCopyButton(textBox, record.RecordType));
                    pnl.Controls.Add(NewShowPasswordButton(textBox));

                    yH = textBox.Height;
                }
                break;

                case RecordType.Password: {
                    var textBox = NewTextBox(labelWidth, y, record);
                    textBox.UseSystemPasswordChar = true;
                    pnl.Controls.Add(textBox);

                    pnl.Controls.Add(NewCopyButton(textBox, record.RecordType));
                    pnl.Controls.Add(NewConfigureButton(textBox, delegate {
                            using (var frm = new PasswordDetailsForm(this.Item, textBox.ReadOnly)) {
                                frm.ShowDialog(this);
                            }
                        }, "Password policy configuration."));
                    pnl.Controls.Add(NewShowPasswordButton(textBox));
                    pnl.Controls.Add(NewGeneratePasswordButton(textBox));

                    void showPasswordWarnings()
                    {
                        if (BadPasswords.IsCommon(textBox.Text, out var matchedPassword))
                        {
                            erp.SetIconAlignment(textBox, ErrorIconAlignment.MiddleLeft);
                            erp.SetIconPadding(textBox, SystemInformation.BorderSize.Width);
                            erp.SetError(textBox, $"Password is similar to a common password ({matchedPassword}).");
                        }
                        else
                        {
                            erp.SetError(textBox, null);
                        }
                    }

                    showPasswordWarnings();
                    textBox.TextChanged += delegate { showPasswordWarnings(); };

                    yH = textBox.Height;
                }
                break;

                case RecordType.Url: {
                    var textBox = NewTextBox(labelWidth, y, record, urlLookAndFeel: true);
                    pnl.Controls.Add(textBox);

                    pnl.Controls.Add(NewCopyFilteredButton(textBox, record.RecordType, copyText: delegate { return(Execute.NormalizeUrl(textBox.Text)); }));
                    pnl.Controls.Add(NewExecuteUrlButton(textBox));
                    pnl.Controls.Add(NewExecuteUrlQRButton(textBox));

                    yH = textBox.Height;
                }
                break;

                case RecordType.EmailAddress: {
                    var textBox = NewTextBox(labelWidth, y, record, urlLookAndFeel: true);
                    pnl.Controls.Add(textBox);

                    pnl.Controls.Add(NewCopyButton(textBox, record.RecordType));
                    pnl.Controls.Add(NewExecuteEmailButton(textBox));

                    yH = textBox.Height;
                }
                break;

                case RecordType.Notes: {
                    var textBox = NewTextBox(labelWidth, y, record, multiline: true);
                    pnl.Controls.Add(textBox);

                    yH = textBox.Height;
                }
                break;

                case RecordType.TwoFactorKey: {
                    var bytes   = record.GetBytes();
                    var textBox = NewTextBox(labelWidth, y, record, text: OneTimePassword.ToBase32(bytes, bytes.Length, SecretFormatFlags.Spacing | SecretFormatFlags.Padding));
                    textBox.UseSystemPasswordChar = true;
                    pnl.Controls.Add(textBox);
                    Array.Clear(bytes, 0, bytes.Length);

                    pnl.Controls.Add(NewCopyFilteredButton(textBox, record.RecordType, tipText: "Copy two-factor number to clipboard.", copyText: delegate { return(Helpers.GetTwoFactorCode(textBox.Text)); }));
                    pnl.Controls.Add(NewViewTwoFactorCode(textBox));
                    pnl.Controls.Add(NewExecuteOAuthQRButton(textBox));
                    pnl.Controls.Add(NewShowPasswordButton(textBox, tipText: "Show two-factor key."));

                    yH = textBox.Height;
                }
                    if (Settings.ShowNtpDriftWarning && !bwCheckTime.IsBusy)
                    {
                        bwCheckTime.RunWorkerAsync();
                    }
                    break;

                case RecordType.CreditCardNumber: {
                    var textBox = NewTextBox(labelWidth, y, record);
                    pnl.Controls.Add(textBox);

                    pnl.Controls.Add(NewCopyFilteredButton(textBox, record.RecordType, allowedCopyCharacters: Helpers.NumberCharacters, tipText: "Copy only numbers to clipboard."));
                    pnl.Controls.Add(NewCopyButton(textBox, record.RecordType));

                    yH = textBox.Height;
                }
                break;


                case RecordType.QRCode: {
                    var textBox = NewTextBox(labelWidth, y, record);
                    pnl.Controls.Add(textBox);

                    pnl.Controls.Add(NewExecuteQRButton(textBox));

                    yH = textBox.Height;
                }
                break;

                case RecordType.RunCommand: {
                    var textBox = NewTextBox(labelWidth, y, record);
                    pnl.Controls.Add(textBox);

                    pnl.Controls.Add(NewExecuteCommandButton(textBox));

                    yH = textBox.Height;
                }
                break;

                default:
                    yH = label.Height;
                    break;
                }

                pnl.Controls.Add(label);

                y += yH + (label.Height / 4);
            }

            if (pnl.VerticalScroll.Visible == true)
            {
                foreach (Control control in pnl.Controls)
                {
                    var label = control as Label;
                    if (label == null)
                    {
                        control.Left -= SystemInformation.VerticalScrollBarWidth;
                    }
                }
            }

            pnl.Visible = true;

            if (this.IsNew)
            {
                titleTextBox.Select();
            }
        }
예제 #41
0
        public async void StartSwarmChain()
        {
            var max = 10;

            if (InputBox.Show("how many?", "how many?", ref max) != DialogResult.OK)
            {
                return;
            }

            // kill old session
            try
            {
                simulator.ForEach(a =>
                {
                    try
                    {
                        a.Kill();
                    }
                    catch { }
                });
            }
            catch
            {
            }

            var exepath = CheckandGetSITLImage("ArduCopter.elf");
            var model   = "+";

            var config = await GetDefaultConfig(model);

            max--;

            for (int a = (int)max; a >= 0; a--)
            {
                var extra = " --disable-fgview -r50";

                if (!string.IsNullOrEmpty(config))
                {
                    extra += @" --defaults """ + config + @",identity.parm"" -P SERIAL0_PROTOCOL=2 -P SERIAL1_PROTOCOL=2 ";
                }

                var home = new PointLatLngAlt(markeroverlay.Markers[0].Position).newpos((double)NUM_heading.Value, a * 4);

                if (max == a)
                {
                    extra += String.Format(
                        " -M{4} -s1 --home {3} --instance {0} --uartA tcp:0 {1} -P SYSID_THISMAV={2} ",
                        a, "", a + 1, BuildHomeLocation(home, (int)NUM_heading.Value), model);
                }
                else
                {
                    extra += String.Format(
                        " -M{4} -s1 --home {3} --instance {0} --uartA tcp:0 {1} -P SYSID_THISMAV={2} ",
                        a, "--uartD tcpclient:127.0.0.1:" + (5772 + 10 * a), a + 1,
                        BuildHomeLocation(home, (int)NUM_heading.Value), model);
                }

                string simdir = sitldirectory + model + (a + 1) + Path.DirectorySeparatorChar;

                Directory.CreateDirectory(simdir);

                File.WriteAllText(simdir + "identity.parm", String.Format(@"SERIAL0_PROTOCOL=2
SERIAL1_PROTOCOL=2
SYSID_THISMAV={0}
SIM_TERRAIN=0
TERRAIN_ENABLE=0
SCHED_LOOP_RATE=50
SIM_RATE_HZ=400
SIM_DRIFT_SPEED=0
SIM_DRIFT_TIME=0
", a + 1));

                string path = Environment.GetEnvironmentVariable("PATH");

                Environment.SetEnvironmentVariable("PATH", sitldirectory + ";" + simdir + ";" + path,
                                                   EnvironmentVariableTarget.Process);

                Environment.SetEnvironmentVariable("HOME", simdir, EnvironmentVariableTarget.Process);

                ProcessStartInfo exestart = new ProcessStartInfo();
                exestart.FileName         = await exepath;
                exestart.Arguments        = extra;
                exestart.WorkingDirectory = simdir;
                exestart.WindowStyle      = ProcessWindowStyle.Minimized;
                exestart.UseShellExecute  = true;

                File.AppendAllText(Settings.GetUserDataDirectory() + "sitl.bat",
                                   "mkdir " + (a + 1) + "\ncd " + (a + 1) + "\n" + @"""" + await exepath + @"""" + " " + extra + " &\n");

                File.AppendAllText(Settings.GetUserDataDirectory() + "sitl1.sh",
                                   "mkdir " + (a + 1) + "\ncd " + (a + 1) + "\n" + @"""../" +
                                   Path.GetFileName(await exepath).Replace("C:", "/mnt/c").Replace("\\", "/").Replace(".exe", ".elf") + @"""" + " " +
                                   extra.Replace("C:", "/mnt/c").Replace("\\", "/") + " &\nsleep .3\ncd ..\n");

                simulator.Add(System.Diagnostics.Process.Start(exestart));
            }

            System.Threading.Thread.Sleep(2000);

            MainV2.View.ShowScreen(MainV2.View.screens[0].Name);

            try
            {
                var client = new Comms.TcpSerial();

                client.client = new TcpClient("127.0.0.1", 5760);

                MainV2.comPort.BaseStream = client;

                SITLSEND = new UdpClient("127.0.0.1", 5501);

                Thread.Sleep(200);

                MainV2.instance.doConnect(MainV2.comPort, "preset", "5760", false);

                try
                {
                    MainV2.comPort.getParamListAsync((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent);
                }
                catch
                {
                }

                return;
            }
            catch
            {
                CustomMessageBox.Show(Strings.Failed_to_connect_to_SITL_instance, Strings.ERROR);
                return;
            }
        }
예제 #42
0
 private void InputBox_MouseDown(object sender, MouseButtonEventArgs e)
 {
     InputBox.Focusable  = true;
     InputBox.CaretIndex = InputBox.CaretIndex;
     InputBox.Focus();
 }
예제 #43
0
        private void todayNewsList_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            title = todayNewsList.Text;
            string url            = Convert.ToString(result[title]);
            string dictationCount = "";
            string script         = "";
            int    x = this.Left;
            int    y = this.Top;

            resultInput resultIn    = new resultInput();
            InputBox    inputbox    = new InputBox();
            bool        patternBool = false;

            userFile uf = new userFile();

            title = toAscii(title);

            string          mp3Url, content;
            DataSet         ds      = new DataSet();
            string          strConn = "Server=203.255.3.244;Database=testDB;Uid=root;Pwd=thsdydtjr2;";
            MySqlConnection conn    = new MySqlConnection(strConn);

            string           sql  = "SELECT content,mp3url FROM testTable where title=\"\'" + title + "\'\"";
            MySqlDataAdapter adpt = new MySqlDataAdapter(sql, conn);

            adpt.Fill(ds, "row");

            mp3Url  = "";
            content = "";
            foreach (DataRow r in ds.Tables[0].Rows)
            {
                mp3Url = (string)r["mp3url"];
                mp3Url = mp3Url.Substring(1, mp3Url.Length - 2);
                Console.WriteLine(mp3Url);
                content = (string)r["content"];
            }

            conn.Close();

            uf.mp3DownLoad(title, mp3Url);

            uf.createReadList(title, mp3Url);
            //script = uf.createScript(title);                // parsing 부분을 쓰레드를 추가하여, 백그라운드로 처리. 그 이후에 스피너를 보여준다.
            script = content.Substring(1, content.Length - 4);                                   // 스피너는 gif 혹은 다이렉트X 를 이용하여 만들어준다.

            string[] splitScript = script.Split(' ');

            int maxWordScript = splitScript.Length;

            bool checkSelectRange = false;

            tabControl1.SelectedIndex = 1;
            do
            {
                resultIn = inputbox.Show("몇개의 단어를 비우시겠습니까?\n 1-" + maxWordScript + " 안에서 선택해 주세요.", "딕테이션 1.0", "", x + 100, y + 100);

                if (!resultIn.getClickCheck())
                {
                    break;
                }

                string Pattern = @"^[0-9]*$";

                if (!Regex.IsMatch(resultIn.getTextResult(), Pattern))
                {
                    MessageBox.Show("숫자만 입력 가능합니다.");
                    patternBool = true;
                }
                else
                {
                    patternBool = false;
                }


                if (!patternBool)
                {
                    if (resultIn.getTextResult().Equals("") || resultIn.getTextResult().Equals("0"))
                    {
                        MessageBox.Show("0개를 비울 수는 없습니다.");
                        checkSelectRange = false;
                    }
                    else if (Int32.Parse(resultIn.getTextResult()) > maxWordScript)
                    {
                        MessageBox.Show("최대치를 벗어났습니다.");
                        checkSelectRange = false;
                    }
                    else
                    {
                        checkSelectRange = true;
                    }
                }
            } while (!checkSelectRange || patternBool);

            if (!resultIn.getClickCheck())
            {
                this.tabControl1.SelectedIndex = 0;
            }
            else
            {
                /*
                 * do
                 * {
                 *  dictationCount = Microsoft.VisualBasic.Interaction.InputBox("몇개의 단어를 비우시겠습니까?", "딕테이션 1.0", "", x, y);
                 *
                 *  //Console.Write(dictationCount.Equals(""));
                 *  if (dictationCount.Equals("0") || dictationCount.Equals(""))
                 *      MessageBox.Show("0개를 비울 수는 없습니다.");
                 *
                 * } while (dictationCount.Equals("0") || dictationCount.Equals(""));
                 */

                dictationCount = resultIn.getTextResult();
                script         = toolClass.createDictation(script, dictationCount);

                article.Text = script;
                article.Font = new Font(article.Font, FontStyle.Regular);

                uf.mp3Start(title);
                playStatus = true;
                fileOb     = uf.getFileDate();
                fileLength = uf.getCalcuratorLength();

                macTrackBar1.Maximum = (int)fileLength;
                timer1.Start();
            }
        }
예제 #44
0
        private static void HandleVariableCommand(ExtendedCommand command, InputSimulator iis, VirtualKeyCodeContainer macro, WriterSettings settings)
        {
            string upperExtendedData = macro.ExtendedData.ToUpperInvariant();

            // Variables
            if (command == ExtendedCommand.EXTENDED_MACRO_VARIABLE_INPUT)
            {
                string defaultValue = String.Empty;
                if (!String.IsNullOrEmpty(upperExtendedData) && dicVariables.ContainsKey(upperExtendedData))
                {
                    defaultValue = dicVariables[upperExtendedData];
                }

                using InputBox input = new InputBox("Variable Input", $"Enter value for \"{upperExtendedData}\":", defaultValue);
                input.ShowDialog();

                // Value exists (cancel button was NOT pressed)
                if (!string.IsNullOrEmpty(input.Input))
                {
                    dicVariables[upperExtendedData] = input.Input;
                }
            }
            else if (command == ExtendedCommand.EXTENDED_MACRO_VARIABLE_OUTPUT)
            {
                if (dicVariables.ContainsKey(upperExtendedData))
                {
                    SuperMacroWriter textWriter = new SuperMacroWriter();
                    textWriter.SendInput(dicVariables[upperExtendedData], settings, null, false);
                }
                else
                {
                    Logger.Instance.LogMessage(TracingLevel.WARN, $"Variable Output called for {upperExtendedData} without an Input beforehand");
                }
            }
            else if (command == ExtendedCommand.EXTENDED_MACRO_VARIABLE_UNSETALL)
            {
                dicVariables.Clear();
            }
            else if (command == ExtendedCommand.EXTENDED_MACRO_VARIABLE_UNSET)
            {
                if (string.IsNullOrEmpty(upperExtendedData))
                {
                    Logger.Instance.LogMessage(TracingLevel.WARN, $"Variable Unset called without variable name");
                    return;
                }
                if (dicVariables.ContainsKey(upperExtendedData))
                {
                    dicVariables.Remove(upperExtendedData);
                }
            }
            else if (command == ExtendedCommand.EXTENDED_MACRO_VARIABLE_SET || command == ExtendedCommand.EXTENDED_MACRO_VARIABLE_SET_FROM_FILE)
            {
                if (string.IsNullOrEmpty(macro.ExtendedData))
                {
                    Logger.Instance.LogMessage(TracingLevel.WARN, $"Variable Set called without variable name");
                    return;
                }

                var splitData = macro.ExtendedData.Split(new char[] { ':' }, 2);
                if (splitData.Length != 2)
                {
                    Logger.Instance.LogMessage(TracingLevel.WARN, $"Variable Set called without incorrect extended data: {macro.ExtendedData}");
                    return;
                }
                string varInput = splitData[1];

                // Set From File but file doesn't exist
                if (command == ExtendedCommand.EXTENDED_MACRO_VARIABLE_SET_FROM_FILE && !File.Exists(splitData[1]))
                {
                    Logger.Instance.LogMessage(TracingLevel.WARN, $"Variable SetFromFile called but file does not exist {splitData[1]}");
                    return;
                }
                else if (command == ExtendedCommand.EXTENDED_MACRO_VARIABLE_SET_FROM_FILE) // File DOES exist
                {
                    varInput = File.ReadAllText(splitData[1]);
                }

                dicVariables[splitData[0].ToUpperInvariant()] = varInput;
            }
            else if (command == ExtendedCommand.EXTENDED_MACRO_VARIABLE_SET_FROM_CLIPBOARD)
            {
                var value = ReadFromClipboard();

                // Value exists (cancel button was NOT pressed)
                if (!string.IsNullOrEmpty(value))
                {
                    dicVariables[upperExtendedData] = value;
                }
            }
            else if (command == ExtendedCommand.EXTENDED_MACRO_VARIABLE_OUTPUT_TO_FILE)
            {
                if (string.IsNullOrEmpty(macro.ExtendedData))
                {
                    Logger.Instance.LogMessage(TracingLevel.WARN, $"OutputToFile called without any params");
                    return;
                }

                var splitData = macro.ExtendedData.Split(new char[] { ':' }, 2);
                if (splitData.Length != 2)
                {
                    Logger.Instance.LogMessage(TracingLevel.WARN, $"OutputToFile called without incorrect extended data: {macro.ExtendedData}");
                    return;
                }

                string variableName = splitData[0].ToUpperInvariant();
                string fileName     = splitData[1];

                // Check if variable exists
                if (!dicVariables.ContainsKey(variableName))
                {
                    Logger.Instance.LogMessage(TracingLevel.WARN, $"OutputToFile called without non existing variable: {variableName}");
                    return;
                }

                // Try to save the data in the variable to the filename
                try
                {
                    File.WriteAllText(fileName, dicVariables[variableName]);
                }
                catch (Exception ex)
                {
                    Logger.Instance.LogMessage(TracingLevel.WARN, $"OutputToFile exception: {macro.ExtendedData} {ex}");
                }
                return;
            }
            else
            {
                Logger.Instance.LogMessage(TracingLevel.ERROR, $"HandleVariableCommand - Invalid command {command}");
            }
        }
예제 #45
0
파일: Form1.cs 프로젝트: Daoi/Scrabble
        //Dropping letter on board
        private void Button_DragDrop(object sender, DragEventArgs e)
        {
            bool   blankTile = false;
            Button btn       = (Button)sender;//The tile the letter is being placed on

            int[] index = BoardHandler.getRowCol(int.Parse(btn.Tag.ToString()));

            //Make sure an adjacent tile contains a letter or is the center piece
            if (!TilePlacement.CheckAdjacent(index[0], index[1], gameBoard))
            {
                e.Effect = DragDropEffects.None;
                return;
            }
            //Save premodified values
            boardAtTurnStart.Add(btn, btn.Text);
            handAtTurnStart.Add(currentTile, currentTile.Text);

            if (currentTile.Text == " ")
            {
                InputBox.SetLanguage(InputBox.Language.English);
                DialogResult res = InputBox.ShowDialog("Select a letter for your tile:",
                                                       "Select a letter",                                                                //Text message (mandatory), Title (optional)
                                                       InputBox.Icon.Information,                                                        //Set icon type (default info)
                                                       InputBox.Buttons.Ok,                                                              //Set buttons (default ok)
                                                       InputBox.Type.ComboBox,                                                           //Set type (default nothing)
                                                       new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
                                                                      "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }, //String field as ComboBox items (default null)
                                                       false,                                                                            //Set visible in taskbar (default false)
                                                       new System.Drawing.Font("Calibri", 10F, System.Drawing.FontStyle.Bold));          //Set font (default by system)
                currentTile.SetTileLetter(InputBox.ResultValue);
                blankTile = true;
            }

            //If it's a preimum board tile, record the multiplier
            if (btn.Text.Equals("Double Word Score") || btn.Text.Equals("*"))
            {
                scoreMultiplier *= 2;
            }
            else if (btn.Text.Equals("Triple Word Score"))
            {
                scoreMultiplier *= 3;
            }
            //Calculate value for premium tiles
            score += CalculateScore.CaluclatePlacedTileScore(btn, currentTile);
            tilesThisTurn.Add(currentTile.Text);

            //Potentially useless
            currentTile.SetBoardPosition(int.Parse(btn.Tag.ToString()));
            //Update board tile
            ib.addTile(new LetterTile(currentTile.Text, currentTile.GetBoardPosition()));

            if (blankTile)
            {
                btn.Text = currentTile.Text;
            }
            else
            {
                btn.Text = e.Data.GetData(DataFormats.StringFormat).ToString();
            }

            btn.AllowDrop = false;
            placements.Add(int.Parse(btn.Tag.ToString()));
            currentTile.Text = "";
        }
예제 #46
0
        private void InputBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string consoleBeforeCall = OutputBox.Text;

                // TODO: Maybe make these try-catches more general
                if (!string.IsNullOrWhiteSpace(InputBox.Text))
                {
                    if (InputBox.Text.Contains("emu.frameadvance("))
                    {
                        ConsoleLog("emu.frameadvance() can not be called from the console");
                        return;
                    }

                    LuaSandbox.Sandbox(null, () =>
                    {
                        LuaImp.ExecuteString($"console.log({InputBox.Text})");
                    }, () =>
                    {
                        LuaSandbox.Sandbox(null, () =>
                        {
                            LuaImp.ExecuteString(InputBox.Text);

                            if (OutputBox.Text == consoleBeforeCall)
                            {
                                ConsoleLog("Command successfully executed");
                            }
                        });
                    });

                    _consoleCommandHistory.Insert(0, InputBox.Text);
                    _consoleCommandHistoryIndex = -1;
                    InputBox.Clear();
                }
            }
            else if (e.KeyCode == Keys.Up)
            {
                if (_consoleCommandHistoryIndex < _consoleCommandHistory.Count - 1)
                {
                    _consoleCommandHistoryIndex++;
                    InputBox.Text = _consoleCommandHistory[_consoleCommandHistoryIndex];
                    InputBox.Select(InputBox.Text.Length, 0);
                }

                e.Handled = true;
            }
            else if (e.KeyCode == Keys.Down)
            {
                if (_consoleCommandHistoryIndex == 0)
                {
                    _consoleCommandHistoryIndex--;
                    InputBox.Text = "";
                }
                else if (_consoleCommandHistoryIndex > 0)
                {
                    _consoleCommandHistoryIndex--;
                    InputBox.Text = _consoleCommandHistory[_consoleCommandHistoryIndex];
                    InputBox.Select(InputBox.Text.Length, 0);
                }

                e.Handled = true;
            }
            else if (e.KeyCode == Keys.Tab)
            {
                ProcessTabKey(false);
                e.Handled = true;
            }
        }
예제 #47
0
        public MainViewModel()
        {
            // ファイルから読む体で
            userDict.Add("111", new UserModel("111", "社会人P")
            {
                Color = Colors.LightGreen
            });
            userDict.Add("222", new UserModel("222", "八百屋"));

            Comments = model.Comments.ToReadOnlyReactiveCollection(comment =>
            {
                if (!userDict.TryGetValue(comment.ID, out var user))
                {
                    user = new UserModel(comment.ID);
                    userDict.Add(user.ID, user);
                }

                return(new CommentViewModel(comment, user));
            }).AddTo(disposable);

            #region Command
            NameChangeCommand.Subscribe(obj =>
            {
                var menuItem = obj as MenuItem;
                var comment  = menuItem.DataContext as CommentViewModel;
                var ib       = new InputBox
                {
                    DataContext = comment,
                    Text        = comment.Name.Value,
                };

                if (ib.ShowDialog() == true)
                {
                    comment.Name.Value = ib.Text;
                }
            });

            ColorChangeCommand.Subscribe(obj =>
            {
                var menuItem        = obj as MenuItem;
                var comment         = menuItem.DataContext as CommentViewModel;
                comment.Color.Value = (Color)menuItem.Tag;
            });

            ConnectCommand = IsRunning.Select(x => !x).ToAsyncReactiveCommand();
            ConnectCommand.Subscribe(async _ =>
            {
                await model.ConnectAsync("lv1234567");
                IsRunning.Value = true;
            }).AddTo(disposable);

            DisconnectCommand = IsRunning.ToReactiveCommand();
            DisconnectCommand.Subscribe(_ =>
            {
                model.Disconnect();
                IsRunning.Value = false;
            }).AddTo(disposable);
            #endregion

            ConnectCommand.Execute();
        }
예제 #48
0
        /// <summary>
        /// Creates an element from the archetype and adds the element to the node.
        /// </summary>
        /// <param name="arch">The element archetype.</param>
        /// <returns>The created element. Null if the archetype is invalid.</returns>
        public ISurfaceNodeElement AddElement(NodeElementArchetype arch)
        {
            ISurfaceNodeElement element = null;

            switch (arch.Type)
            {
            case NodeElementType.Input:
                element = new InputBox(this, arch);
                break;

            case NodeElementType.Output:
                element = new OutputBox(this, arch);
                break;

            case NodeElementType.BoolValue:
                element = new BoolValue(this, arch);
                break;

            case NodeElementType.FloatValue:
                element = new FloatValue(this, arch);
                break;

            case NodeElementType.IntegerValue:
                element = new IntegerValue(this, arch);
                break;

            case NodeElementType.ColorValue:
                element = new ColorValue(this, arch);
                break;

            case NodeElementType.ComboBox:
                element = new ComboBoxElement(this, arch);
                break;

            case NodeElementType.Asset:
                element = new AssetSelect(this, arch);
                break;

            case NodeElementType.Text:
                element = new TextView(this, arch);
                break;

            case NodeElementType.TextBox:
                element = new TextBoxView(this, arch);
                break;

            case NodeElementType.SkeletonBoneIndexSelect:
                element = new SkeletonBoneIndexSelectElement(this, arch);
                break;

            case NodeElementType.BoxValue:
                element = new BoxValue(this, arch);
                break;

            case NodeElementType.EnumValue:
                element = new EnumValue(this, arch);
                break;

            case NodeElementType.SkeletonNodeNameSelect:
                element = new SkeletonNodeNameSelectElement(this, arch);
                break;

            case NodeElementType.Actor:
                element = new ActorSelect(this, arch);
                break;

            case NodeElementType.UnsignedIntegerValue:
                element = new UnsignedIntegerValue(this, arch);
                break;
                //default: throw new NotImplementedException("Unknown node element type: " + arch.Type);
            }
            if (element != null)
            {
                AddElement(element);
            }

            return(element);
        }
예제 #49
0
        async Task <SearchResult> query_item_by_name()
        {
            string itemName = null;

            while (string.IsNullOrEmpty(itemName))
            {
                using (InputBox input = new InputBox("Please enter the item name", false))
                    if (input.ShowDialog(this) == DialogResult.OK)
                    {
                        itemName = input.Value;
                    }

                if (string.IsNullOrEmpty(itemName))
                {
                    if (MessageBox.Show("You must enter an item name to continue!", "Empty Name", MessageBoxButtons.OKCancel, MessageBoxIcon.Hand) == DialogResult.Cancel)
                    {
                        break;
                    }
                }
            }

            string selectedName = null;

            if (string.IsNullOrEmpty(itemName))
            {
                MessageBox.Show("You have entered an invalid item name!", "Invalid Item Name", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                List <SearchResult> searchResults = await queryDBForItems(itemName);

                if (searchResults.Count == 0)
                {
                    MessageBox.Show("Failed to query items from the database!", "SQL Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    List <string> resultNames = searchResults.Select(r => r.Name).ToList();

                    if (resultNames.Count == 0)
                    {
                        MessageBox.Show("Failed to query item names from search results!", "Result Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        using (ListSelect listSelect = new ListSelect("Please select an item", resultNames))
                            if (listSelect.ShowDialog(this) == DialogResult.OK)
                            {
                                selectedName = listSelect.SelectedText;
                            }

                        if (string.IsNullOrEmpty(selectedName))
                        {
                            MessageBox.Show("Invalid selected name!", "Invalid Selection", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            return(searchResults.Find(r => r.Name == selectedName));
                        }
                    }
                }
            }

            return(null);
        }
예제 #50
0
        async Task <MarketEntry> create_new_entry(int sort_id, string market_name)
        {
            MarketEntry entry = new MarketEntry(sort_id, market_name);

            DialogResult dlgResult = MessageBox.Show("Would you like to search for the item code by name?", "Input Required", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

            if (dlgResult == DialogResult.Cancel)
            {
                return(null);
            }
            else if (dlgResult == DialogResult.Yes)
            {
                SearchResult result = await query_item_by_name();

                if (result != null)
                {
                    entry.ItemName        = result.Name;
                    entry.Code            = result.ID;
                    entry.Price           = result.Price;
                    entry.HuntaholicPoint = result.HuntaholicPoint;

                    if (useArena)
                    {
                        entry.ArenaPoint = result.ArenaPoint;
                    }
                }
            }
            else if (dlgResult == DialogResult.No)
            {
                int itemCode = 0;

                while (itemCode == 0)
                {
                    using (InputBox input = new InputBox("Please enter the item code", false))
                    {
                        if (input.ShowDialog(this) == DialogResult.OK)
                        {
                            if (int.TryParse(input.Value, out itemCode))
                            {
                                entry.Code = itemCode;
                            }
                            else
                            {
                                if (MessageBox.Show("You have enter an invalid item code!\n\nPlease try again.", "Invalid Code", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == DialogResult.Cancel)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }

                if (itemCode == 0)
                {
                    MessageBox.Show("Invalid Item Code!", "Invalid Code", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    entry.Code = itemCode;

                    SearchResult result = await queryItemInfo(itemCode);

                    if (result == null)
                    {
                        MessageBox.Show("Failed to item information from the database!", "SQL Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        entry.ItemName        = result.Name;
                        entry.Price           = result.Price;
                        entry.HuntaholicPoint = result.HuntaholicPoint;

                        if (useArena)
                        {
                            entry.ArenaPoint = result.ArenaPoint;
                        }
                    }
                }
            }

            return(entry);
        }
예제 #51
0
        /// <summary>
        /// This method permits, on user click, to perform two type of actions.
        /// <list type="On click">
        ///     <item> The user can iterate with a combo list full of all possible value for this tag.</item>
        ///     <item> It appears a open dialog form where you can specify which path you want indicate.</item>
        ///     <item> It appears an input box where you can insert custom value</item>
        /// </list>
        /// </summary>
        /// <param name="sender">Object that is a dataGridView type</param>
        /// <param name="e">This contains event info about data cell</param>
        private void dgvConfig_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            Boolean validClick = (e.RowIndex != -1 && e.ColumnIndex != -1); //Make sure the clicked row/column is valid.
            // Check to make sure the cell clicked is the cell containing the combobox
            //if ((e.ColumnIndex == kColumnActions) && validClick) {
            String myTag         = dgvConfig.Rows[e.RowIndex].Cells[Constants.K_ColumnTag].Value.ToString();
            String myValue       = dgvConfig.Rows[e.RowIndex].Cells[Constants.K_ColumnValue].Value.ToString();
            String myDescription = dgvConfig.Rows[e.RowIndex].Cells[Constants.K_ColumnDescriptionHidden].Value.ToString();

            if ((e.ColumnIndex == Constants.K_ColumnValue) && validClick)
            {
                if (dgvConfig.CurrentCell is DataGridViewComboBoxCell)
                {
                    dgvConfig.ReadOnly = false;
                    dgvConfig.EditMode = DataGridViewEditMode.EditOnEnter;
                }
                else
                {
                    String prompt = "TAG --> " + myTag;
                    if (Trivia.IterateOverList(ListOpenDialog, myTag))
                    {
                        String  Path = String.Empty;
                        Boolean f    = FileUtils.OpenFolder(out Path);

                        if (!f)
                        {
                            return;
                        }

                        if (myValue != Path)
                        {
                            DictionaryUtils.UpdateCustomValue(myTag, Path, myDescription, ref DictionaryAllRows);
                            dgvConfig[Constants.K_ColumnValue, e.RowIndex].Value = Path;
                        }
                    }
                    else if (Trivia.IterateOverList(ListOpenTextBox, myTag))
                    {
                        String         title   = String.Empty;
                        String         content = dgvConfig[Constants.K_ColumnValue, e.RowIndex].Value.ToString();
                        String         tip     = String.Empty;
                        InputBoxResult result  = InputBox.Show(prompt, title, content, tip, new InputBoxValidatingHandler(inputBox_Validating));
                        if ((result.OK) && (content != result.Text))
                        {
                            DictionaryUtils.UpdateCustomValue(myTag, result.Text, myDescription, ref DictionaryAllRows);
                            dgvConfig[Constants.K_ColumnValue, e.RowIndex].Value = result.Text;
                        }
                    }
                    else if (Trivia.IterateOverList(ListOpenCheckBoxList, myTag))
                    {
                        ChkListBox frm = new ChkListBox();

                        //add new prefixes here
                        //String[] defaultValues = new String[46]{ "*.c", "*.cc", "*.cxx", "*.cpp", "*.cs", "*.c++", "*.java", "*.ii", "*.ixx",
                        //                                         "*.ipp", "*.i++", "*.inl", "*.idl", "*.ddl", "*.odl", "*.h", "*.hh",
                        //                                         "*.hxx", "*.hpp", "*.h++", "*.cs", "*.d", "*.php", "*.php4", "*.php5",
                        //                                         "*.phtml", "*.inc", "*.m", "*.markdown", "*.md", "*.mm", "*.dox", "*.py",
                        //                                         "*.pyw", "*.f90", "*.f95", "*.f03", "*.f08", "*.f", "*.for", "*.tcl",
                        //                                         "*.vhd", "*.vhdl", "*.ucf", "*.qsf", "*.ice"};
                        String   content         = dgvConfig[Constants.K_ColumnValue, e.RowIndex].Value.ToString().Trim();
                        String[] checkedElements = content.Split(new Char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);

                        ////remove all spaces in a String array
                        //checkedElements = (from t in checkedElements
                        //                   select t.Trim()).ToArray();

                        frm.prompt        = prompt;
                        frm.checkedValues = checkedElements;
                        //frm.values = defaultValues;
                        frm.ShowDialog();

                        if (!String.IsNullOrEmpty(frm.strRet))
                        {
                            dgvConfig[Constants.K_ColumnValue, e.RowIndex].Value = frm.strRet;
                        }
                    }
                    dgvConfig.ReadOnly = true;
                }
            }
            else
            {
                dgvConfig.ReadOnly = true;
            }

            if (e.ColumnIndex < 2)
            {
                txtDescription.Text = dgvConfig.Rows[e.RowIndex].Cells[Constants.K_ColumnDescriptionHidden].Value.ToString().Replace("\r\n", "");
            }
        }
예제 #52
0
        public override void Initialize(ContentManager Content)
        {
            ShipsInTop = new List <Card>();
            ShipsInBot = new List <Card>();
            layout     = new RelativeLayout();
            Gui        = new GUI(Content);
            Decks      = new List <Deck>();
            int gridRightColumnWidth =
                (int)((int)Game1.self.graphics.PreferredBackBufferWidth * (1 - CardGridWidthMulti)) - 30;
            int gridRightRowHeight = 60;

            int ColumnWidth = (int)((int)Game1.self.graphics.PreferredBackBufferWidth * CardGridWidthMulti * 0.2);
            int rowHeight   = (int)((int)Game1.self.graphics.PreferredBackBufferHeight * CardGridHeightMulti);

            gridTopLeft     = new Grid(5, 3, ColumnWidth, rowHeight);
            gridRight       = new Grid(1, 8, gridRightColumnWidth, gridRightRowHeight);
            gridRightBottom = new Grid();
            int columns = 5;

            gridCenter = new Grid(columns, Game1.self.Modifiers.MaxShipsPerPlayer / columns + 1, ColumnWidth, rowHeight);
            ;
            gridTopLeft.DrawBorder     = true;
            gridRight.DrawBorder       = true;
            gridRightBottom.DrawBorder = false;
            gridCenter.DrawBorder      = true;

            gridTopLeft.BorderSize     = 3;
            gridRight.BorderSize       = 3;
            gridRightBottom.BorderSize = 3;
            gridCenter.BorderSize      = 3;

            gridTopLeft.WitdhAndHeightColumnDependant     = false;
            gridRight.WitdhAndHeightColumnDependant       = false;
            gridRightBottom.WitdhAndHeightColumnDependant = false;
            gridCenter.WitdhAndHeightColumnDependant      = false;

            gridTopLeft.Width     = (int)((int)Game1.self.graphics.PreferredBackBufferWidth * CardGridWidthMulti);
            gridRight.Width       = (int)((int)Game1.self.graphics.PreferredBackBufferWidth * (1 - CardGridWidthMulti) - 30);
            gridRightBottom.Width = gridRight.Width;
            gridCenter.Width      = gridTopLeft.Width;

            gridTopLeft.Height     = (int)((int)Game1.self.graphics.PreferredBackBufferHeight * CardGridHeightMulti);
            gridRight.Height       = (int)((int)Game1.self.graphics.PreferredBackBufferHeight * RightGridHeightMulti);
            gridRightBottom.Height = (int)((int)Game1.self.graphics.PreferredBackBufferHeight * (1 - RightGridHeightMulti) - 30);
            gridCenter.Height      = (int)((int)Game1.self.graphics.PreferredBackBufferHeight * (1 - CardGridHeightMulti) - 30);


            gridTopLeft.Origin     = new Point(10, 10);
            gridRight.Origin       = new Point((int)(Game1.self.graphics.PreferredBackBufferWidth * CardGridWidthMulti + 20), 10);
            gridRightBottom.Origin = new Point((int)(Game1.self.graphics.PreferredBackBufferWidth * CardGridWidthMulti + 20),
                                               (int)(Game1.self.graphics.PreferredBackBufferHeight * RightGridHeightMulti + 20));
            gridCenter.Origin = new Point(10, (int)(Game1.self.graphics.PreferredBackBufferHeight - gridCenter.Height - 10));

            Button b = new Button(new Point(0, 0), (int)(gridRightBottom.Width * 0.5 - gridCenter.columnOffset), (int)((gridRightBottom.Height * 0.75) * 0.5 - gridCenter.rowOffset), Game1.self.GraphicsDevice,
                                  Gui, Gui.mediumFont, true)
            {
                Text = "Add"
            };
            Button b2 = new Button(new Point(0, 0), (int)(gridRightBottom.Width * 0.5 - gridCenter.columnOffset), (int)((gridRightBottom.Height * 0.75) * 0.5 - gridCenter.rowOffset), Game1.self.GraphicsDevice,
                                   Gui, Gui.mediumFont, true)
            {
                Text = "Save"
            };
            Button b3 = new Button(new Point(0, 0), (int)(gridRightBottom.Width * 0.5 - gridCenter.columnOffset), (int)((gridRightBottom.Height * 0.75) * 0.5 - gridCenter.rowOffset), Game1.self.GraphicsDevice,
                                   Gui, Gui.mediumFont, true)
            {
                Text = "Remove"
            };
            Button b4 = new Button(new Point(0, 0), (int)(gridRightBottom.Width * 0.5 - gridCenter.columnOffset), (int)((gridRightBottom.Height * 0.75) * 0.5 - gridCenter.rowOffset), Game1.self.GraphicsDevice,
                                   Gui, Gui.mediumFont, true)
            {
                Text = "Exit"
            };

            Button up = new Button(new Point(gridTopLeft.Origin.X + (int)(gridTopLeft.Width) - 60, gridTopLeft.Origin.Y), 60, 30, Game1.self.GraphicsDevice,
                                   Gui, Gui.mediumFont, true)
            {
                Text = "up"
            };
            Button down = new Button(new Point(gridTopLeft.Origin.X + (int)(gridTopLeft.Width) - 60, gridTopLeft.Origin.Y + 30), 60, 30, Game1.self.GraphicsDevice,
                                     Gui, Gui.mediumFont, true)
            {
                Text = "down"
            };



            Button upCenter = new Button(new Point(gridCenter.Origin.X + (int)(gridCenter.Width) - 60, gridCenter.Origin.Y), 60, 30, Game1.self.GraphicsDevice,
                                         Gui, Gui.mediumFont, true)
            {
                Text = "up"
            };
            Button downCenter = new Button(new Point(gridCenter.Origin.X + (int)(gridCenter.Width) - 60, gridCenter.Origin.Y + 30), 60, 30, Game1.self.GraphicsDevice,
                                           Gui, Gui.mediumFont, true)
            {
                Text = "down"
            };

            DeckInputBox           = new InputBox(new Point(), gridRightBottom.Width, (int)(gridRightBottom.Height * 0.25), Game1.self.GraphicsDevice, Gui, Gui.mediumFont, false);
            DeckInputBox.TextLimit = 30;
            DeckInputBox.BasicText = "Deck name";
            up.Update();
            down.Update();
            upCenter.Update();
            downCenter.Update();

            up.clickEvent         += UpClick;
            down.clickEvent       += DownClick;
            upCenter.clickEvent   += UpClickCenter;
            downCenter.clickEvent += DownClickCenter;

            Clickable.Add(up);
            Clickable.Add(down);
            Clickable.Add(upCenter);
            Clickable.Add(downCenter);

            RelativeLayout rl = new RelativeLayout();

            rl.AddChild(up);
            rl.AddChild(down);
            rl.AddChild(upCenter);
            rl.AddChild(downCenter);

            Clickable.Add(b4);
            Clickable.Add(DeckInputBox);
            b4.clickEvent += OnExit;
            b.clickEvent  += OnAdd;
            b2.clickEvent += OnSave;
            b3.clickEvent += OnRemove;
            Clickable.Add(b2);
            Clickable.Add(b);
            Clickable.Add(b3);
            gridRightBottom.AddChild(DeckInputBox, 0, 0, 3);
            gridRightBottom.AddChild(b, 1, 1);
            gridRightBottom.AddChild(b2, 1, 2);
            gridRightBottom.AddChild(b3, 2, 1);
            gridRightBottom.AddChild(b4, 2, 2);
            gridRightBottom.ResizeChildren();
            DeckInputBox.Update();



            layout.AddChild(gridTopLeft);
            layout.AddChild(gridRight);
            layout.AddChild(gridRightBottom);
            layout.AddChild(gridCenter);
            layout.AddChild(rl);

            gridTopLeft.AllVisible  = false;
            gridTopLeft.VisibleRows = 1;

            gridCenter.AllVisible  = false;
            gridCenter.VisibleRows = 5;


            gridTopLeft.ConstantRowsAndColumns = true;
            gridTopLeft.MaxChildren            = true;
            gridTopLeft.ChildMaxAmount         = 15;

            gridCenter.ConstantRowsAndColumns = true;
            gridCenter.MaxChildren            = true;
            gridCenter.ChildMaxAmount         = Game1.self.Modifiers.MaxShipsPerPlayer;

            gridRight.ConstantRowsAndColumns = true;
            gridRight.MaxChildren            = true;
            gridRight.ChildMaxAmount         = 8;

            cardHeight = gridTopLeft.Height;


            /*     //basic test
             *
             * ships = new List<Ship>();
             * Random rndRandom = new Random();
             * for (int i = 0; i < 30; i++)
             * {
             *  Ship ship = new Ship();
             *  ship.Armor = rndRandom.Next(1, 30);
             *  ship.Hp = rndRandom.Next(1, 30);
             *  ships.Add(ship);
             * }
             *
             * List<Ship> Deck1Ships = ships.GetRange(1, 10);
             * Deck BasicDeck = new Deck(new Point(), 20, (int)(gridRight.Height * 0.1),
             *  Game1.self.GraphicsDevice, Gui, Gui.mediumFont, false, "Basic" );
             * Deck1Ships.ForEach(p=> BasicDeck.AddShip(p));
             * BasicDeck.clickEvent += DeckClick;
             * gridRight.AddChild(BasicDeck);
             * Clickable.Add(BasicDeck);
             * gridRight.ResizeChildren();
             *
             *
             */

            popup = new Popup(new Point((int)(Game1.self.graphics.PreferredBackBufferWidth * 0.5), (int)(Game1.self.graphics.PreferredBackBufferHeight * 0.5)), 400, 400, Game1.self.GraphicsDevice, Gui);
            Grid popupGrid = new Grid();

            lbl1 = new Label(popup.Width - 50, 200, Game1.self.GraphicsDevice, Gui, Gui.mediumFont, true);
            Button b1 = new Button(100, 100, Game1.self.GraphicsDevice, Gui, Gui.mediumFont, true)
            {
                Text = "Exit"
            };

            lbl1.DrawBackground = false;
            b1.DrawBackground   = false;
            popup.grid          = popupGrid;
            popupGrid.AddChild(lbl1, 0, 0);
            popupGrid.AddChild(b1, 1, 0);
            b1.clickEvent += onPopupExit;
            Clickable.Add(b1);
            popup.SetToGrid();



            FillBotShips(ships);
            FillBotGrid();

            gridTopLeft.AllVisible  = false;
            gridTopLeft.VisibleRows = 1;

            gridCenter.AllVisible  = false;
            gridCenter.VisibleRows = 5;

            gridCenter.UpdateP();
            gridTopLeft.UpdateP();
        }
예제 #53
0
        private void OnContainerLabelAddTarget(bool ground, Serial serial, Point3D pt, ushort gfx)
        {
            TargetInfo t = new TargetInfo
            {
                Gfx    = gfx,
                Serial = serial,
                Type   = (byte)(ground ? 1 : 0),
                X      = pt.X,
                Y      = pt.Y,
                Z      = pt.Z
            };

            if (t != null && t.Serial.IsItem)
            {
                Item item = World.FindItem(t.Serial);

                if (!item.IsContainer)
                {
                    // must be a container
                    World.Player.SendMessage(MsgLevel.Force, "You must select a container");
                }
                else
                {
                    // add it
                    World.Player.SendMessage(MsgLevel.Force, "Container selected, add label text in Razor");

                    if (InputBox.Show(this, Language.GetString(LocString.SetContainerLabel), Language.GetString(LocString.EnterAName)))
                    {
                        string name = InputBox.GetString();

                        ListViewItem lvItem = new ListViewItem($"{t.Serial.Value}");
                        lvItem.SubItems.Add(new ListViewItem.ListViewSubItem(lvItem, item.Name));
                        lvItem.SubItems.Add(new ListViewItem.ListViewSubItem(lvItem, name));
                        lvItem.SubItems.Add(new ListViewItem.ListViewSubItem(lvItem, string.Empty));

                        int hueIdx = Config.GetInt("ContainerLabelColor");

                        if (hueIdx > 0 && hueIdx < 3000)
                        {
                            lvItem.SubItems[2].BackColor = Ultima.Hues.GetHue(hueIdx - 1).GetColor(HueEntry.TextHueIDX);
                        }
                        else
                        {
                            lvItem.SubItems[2].BackColor = SystemColors.Control;
                        }

                        lvItem.SubItems[2].ForeColor = (lvItem.SubItems[2].BackColor.GetBrightness() < 0.35 ? Color.White : Color.Black);

                        lvItem.UseItemStyleForSubItems = false;

                        containerView.Items.Add(lvItem);

                        NewContainerEntries.Add(new Core.ContainerLabels.ContainerLabel
                        {
                            Hue   = hueIdx,
                            Id    = $"{t.Serial.Value}",
                            Label = name,
                            Type  = item.Name
                        });

                        World.Player.SendMessage(MsgLevel.Force, $"Container {item} labeled as '{name}'");

                        Show();
                    }
                }
            }
            else if (t != null && t.Serial.IsMobile)
            {
                World.Player.SendMessage(MsgLevel.Force, "You shouldn't label other people");
            }
        }
예제 #54
0
 private void Window_Loaded(object sender, RoutedEventArgs e)
 {
     InputBox.Focus();
 }
예제 #55
0
 private void btn_desativacao_Click(object sender, EventArgs e)
 {
     if (bsPneus.Current != null)
     {
         if ((bsPneus.Current as TRegistro_LanPneu).St_registro.ToUpper().Equals("D"))
         {
             return;
         }
         else if ((bsPneus.Current as TRegistro_LanPneu).Status.Equals("MANUTENÇÃO"))
         {
             MessageBox.Show("Não é possível desativar pneus com status em MANUTENÇÃO", "Informativo", MessageBoxButtons.OK, MessageBoxIcon.Information);
             return;
         }
         if (MessageBox.Show("Confirma a desativação do pneu selecionado?", "Pergunta", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
             == DialogResult.Yes)
         {
             try
             {
                 InputBox ibp = new InputBox();
                 ibp.Text = "Motivo Desativação";
                 string motivo = ibp.ShowDialog();
                 if (string.IsNullOrEmpty(motivo))
                 {
                     MessageBox.Show("Obrigatório informar motivo de desativação!", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information);
                     return;
                 }
                 if (motivo.Trim().Length < 10)
                 {
                     MessageBox.Show("Motivo de desativação deve ter mais que 10 caracteres!", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information);
                     return;
                 }
                 (bsPneus.Current as TRegistro_LanPneu).MotivoDesativacao = motivo;
                 if ((bsPneus.Current as TRegistro_LanPneu).Status.Equals("RODANDO"))
                 {
                     using (Componentes.TFQuantidade fQtde = new Componentes.TFQuantidade())
                     {
                         fQtde.Ds_label = "Hodometro final";
                         TpBusca[] tpBuscas = new TpBusca[0];
                         Estruturas.CriarParametro(ref tpBuscas, "a.cd_empresa", (bsPneus.Current as TRegistro_LanPneu).Cd_empresa);
                         Estruturas.CriarParametro(ref tpBuscas, "a.id_pneu", (bsPneus.Current as TRegistro_LanPneu).Id_pneustr);
                         Estruturas.CriarParametro(ref tpBuscas, "a.id_veiculo", (bsPneus.Current as TRegistro_LanPneu).Id_veiculo);
                         Estruturas.CriarParametro(ref tpBuscas, "a.id_rodado", (bsPneus.Current as TRegistro_LanPneu).Id_rodado);
                         fQtde.Vl_default           = Convert.ToDecimal(new CamadaDados.Frota.TCD_MovPneu().BuscarEscalar(tpBuscas, "a.hodometro", "id_mov desc").ToString());
                         fQtde.Vl_Minimo            = fQtde.Vl_default;
                         fQtde.Casas_decimais       = 0;
                         fQtde.St_permitirValorZero = false;
                         if (fQtde.ShowDialog() == DialogResult.OK)
                         {
                             (bsPneus.Current as TRegistro_LanPneu).HodometroDesativacao = Convert.ToInt32(fQtde.Quantidade);
                         }
                         else
                         {
                             MessageBox.Show("Obrigatório informar hodometro para desativação!", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information);
                             return;
                         }
                     }
                 }
                 TCN_LanPneu.Desativacao(bsPneus.Current as TRegistro_LanPneu, null);
                 MessageBox.Show("Pneu desativado com sucesso!", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information);
                 afterBusca();
             }
             catch (Exception ex)
             { MessageBox.Show(ex.Message.Trim(), "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); }
         }
     }
 }
예제 #56
0
        public Task ExecuteAsync(CancellationToken cancellation = default)
        {
            var dialog = new SwitchDialog(branches: repository.Branches.Select(x => x.FriendlyName).OrderBy(x => x).ToArray());

            if (mainThread.Invoke(() => dialog.ShowDialog()) == true && !string.IsNullOrEmpty(dialog.Branch))
            {
                var branch = repository.Branches.FirstOrDefault(x => x.FriendlyName == dialog.Branch);

                var targetBranch          = branch;
                var targetBranchName      = dialog.Branch;
                var overwriteTargetBranch = false;

                // Check if the selected branch is remote
                if (branch?.IsRemote == true)
                {
                    // Get the branch name from the remote
                    targetBranchName = branch.GetName();

                    // Allow the user to create a branch for the remote
                    var createBranchDialog = new InputBox("Create Branch", "Branch")
                    {
                        Text = targetBranchName
                    };
                    if (mainThread.Invoke(() => createBranchDialog.ShowDialog()) == true)
                    {
                        // Check if the new branch already exists
                        targetBranchName = createBranchDialog.Text;
                        targetBranch     = repository.Branches.FirstOrDefault(x =>
                                                                              !x.IsRemote && x.FriendlyName == createBranchDialog.Text);

                        if (targetBranch != null)
                        {
                            // The branch already exist => ask the user to overwrite it
                            var forceDialog = new MessageBox(
                                "Warning",
                                DialogBoxButton.Ok | DialogBoxButton.Cancel,
                                "A branch with this name already exists. Do you want to overwrite it?");

                            overwriteTargetBranch = mainThread.Invoke(() => forceDialog.ShowDialog() == true);
                            if (!overwriteTargetBranch)
                            {
                                return(CancelCheckout());
                            }
                        }
                    }
                    else
                    {
                        return(CancelCheckout());
                    }
                }

                // 1. Check the remote branch if remote was selected
                if (branch?.IsRemote == true)
                {
                    repository.Checkout(branch);
                }

                // 2. Remove the existing branch if the user decided to overwrite it
                if (overwriteTargetBranch && targetBranch != null)
                {
                    eventStream.Push(Status.Create(0.2f, "Removing branch {0}", targetBranch.FriendlyName));
                    repository.Branches.Remove(targetBranch);
                }

                // 3. Create the branch if it does not exist
                if (targetBranch == null)
                {
                    eventStream.Push(Status.Create(0.4f, "Creating branch {0}", targetBranchName));
                    targetBranch = repository.CreateBranch(targetBranchName);
                }

                // 4. Checkout the branch
                eventStream.Push(Status.Create(0.6f, "Swithing to branch {0}", targetBranchName));
                repository.Checkout(targetBranch);

                // 5. Update submodules
                if (dialog.UpdateSubmodules)
                {
                    eventStream.Push(Status.Create(0.8f, "Updating submodules..."));
                    repository.UpdateSubmodules(eventStream: eventStream);
                }

                eventStream.Push(new BranchChanged(targetBranchName));
                eventStream.Push(Status.Succeeded());
            }

            return(Task.CompletedTask);
        }
예제 #57
0
        private void menu_passthrough_Click(object sender, EventArgs e)
        {
            if (listener != null)
            {
                menu_passthrough.Checked = false;
                listener.Stop();
                CustomMessageBox.Show("Stop", "Disabled forwarding");
                listener = null;
                return;
            }

            var port = 500;

            if (InputBox.Show("Enter TCP Port", "Enter TCP Port", ref port) == DialogResult.OK)
            {
                menu_passthrough.Checked = true;

                Task.Run(() =>
                {
                    try
                    {
                        listener = new TcpListener(IPAddress.Any, port);
                        listener.Start();

                        int tcpbps  = 0;
                        int rtcmbps = 0;
                        int combps  = 0;
                        int second  = 0;

                        while (true)
                        {
                            var client     = listener.AcceptTcpClient();
                            client.NoDelay = true;

                            var st = client.GetStream();

                            DroneCAN.DroneCAN.MessageRecievedDel mrd = (frame, msg, id) =>
                            {
                                combps += frame.SizeofEntireMsg;
                                if (frame.MsgTypeID == DroneCAN.DroneCAN.uavcan_equipment_gnss_RTCMStream.UAVCAN_EQUIPMENT_GNSS_RTCMSTREAM_DT_ID)
                                {
                                    var data = msg as DroneCAN.DroneCAN.uavcan_equipment_gnss_RTCMStream;
                                    try
                                    {
                                        rtcmbps += data.data_len;
                                        st.Write(data.data, 0, data.data_len);
                                        st.Flush();
                                    }
                                    catch
                                    {
                                        client = null;
                                    }
                                }

                                if (frame.MsgTypeID == DroneCAN.DroneCAN.ardupilot_gnss_MovingBaselineData.ARDUPILOT_GNSS_MOVINGBASELINEDATA_DT_ID)
                                {
                                    var data = msg as DroneCAN.DroneCAN.ardupilot_gnss_MovingBaselineData;
                                    try
                                    {
                                        rtcmbps += data.data_len;
                                        st.Write(data.data, 0, data.data_len);
                                        st.Flush();
                                    }
                                    catch
                                    {
                                        client = null;
                                    }
                                }
                            };

                            can.MessageReceived -= mrd;
                            can.MessageReceived += mrd;

                            try
                            {
                                while (true)
                                {
                                    if (client.Available > 0)
                                    {
                                        var toread    = Math.Min(client.Available, 128);
                                        byte[] buffer = new byte[toread];
                                        var read      = st.Read(buffer, 0, toread);
                                        foreach (var b in buffer)
                                        {
                                            Console.Write("0x{0:X} ", b);
                                        }

                                        Console.WriteLine();
                                        tcpbps   += read;
                                        var slcan = can.PackageMessageSLCAN(0, 30, 0,
                                                                            new DroneCAN.DroneCAN.uavcan_equipment_gnss_RTCMStream()
                                        {
                                            protocol_id = 3, data = buffer, data_len = (byte)read
                                        });
                                        can.WriteToStreamSLCAN(slcan);
                                    }

                                    Thread.Sleep(1);

                                    if (second != DateTime.Now.Second)
                                    {
                                        Console.WriteLine("tcp:{0} can:{1} data:{2} avail:{3}", tcpbps, combps, rtcmbps,
                                                          client.Available);
                                        tcpbps = combps = rtcmbps = 0;
                                        second = DateTime.Now.Second;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                can.MessageReceived -= mrd;
                                Console.WriteLine(ex);
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        CustomMessageBox.Show(Strings.ERROR, "Forwarder problem " + exception.ToString());
                        if (listener != null)
                        {
                            listener.Stop();
                        }
                        listener = null;
                        this.InvokeIfRequired(() => { menu_passthrough.Checked = true; });
                    }
                });
            }
        }
예제 #58
0
        public async void StartSwarmSeperate()
        {
            var exepath = CheckandGetSITLImage("ArduCopter.elf");
            var model   = "+";

            var config = await GetDefaultConfig(model);

            var max = 10.0;

            if (InputBox.Show("how many?", "how many?", ref max) != DialogResult.OK)
            {
                return;
            }

            max--;

            for (int a = (int)max; a >= 0; a--)
            {
                var extra = " --disable-fgview -r50 ";

                if (!string.IsNullOrEmpty(config))
                {
                    extra += @" --defaults """ + config + @""" -P SERIAL0_PROTOCOL=2 -P SERIAL1_PROTOCOL=2 ";
                }

                var home = new PointLatLngAlt(markeroverlay.Markers[0].Position).newpos((double)NUM_heading.Value, a * 4);

                if (max == a)
                {
                    extra += String.Format(
                        " -M{4} -s1 --home {3} --instance {0} --uartA tcp:0 {1} -P SYSID_THISMAV={2} ",
                        a, "", a + 1, BuildHomeLocation(home, (int)NUM_heading.Value), model);
                }
                else
                {
                    extra += String.Format(
                        " -M{4} -s1 --home {3} --instance {0} --uartA tcp:0 {1} -P SYSID_THISMAV={2} ",
                        a, "" /*"--uartD tcpclient:127.0.0.1:" + (5770 + 10 * a)*/, a + 1,
                        BuildHomeLocation(home, (int)NUM_heading.Value), model);
                }

                string simdir = sitldirectory + model + (a + 1) + Path.DirectorySeparatorChar;

                Directory.CreateDirectory(simdir);

                string path = Environment.GetEnvironmentVariable("PATH");

                Environment.SetEnvironmentVariable("PATH", sitldirectory + ";" + simdir + ";" + path,
                                                   EnvironmentVariableTarget.Process);

                Environment.SetEnvironmentVariable("HOME", simdir, EnvironmentVariableTarget.Process);

                ProcessStartInfo exestart = new ProcessStartInfo();
                exestart.FileName         = await exepath;
                exestart.Arguments        = extra;
                exestart.WorkingDirectory = simdir;
                exestart.WindowStyle      = ProcessWindowStyle.Minimized;
                exestart.UseShellExecute  = true;

                Process.Start(exestart);
            }

            try
            {
                for (int a = (int)max; a >= 0; a--)
                {
                    var mav = new MAVLinkInterface();

                    var client = new Comms.TcpSerial();

                    client.client = new TcpClient("127.0.0.1", 5760 + (10 * (a)));

                    mav.BaseStream = client;

                    //SITLSEND = new UdpClient("127.0.0.1", 5501);

                    Thread.Sleep(200);

                    MainV2.instance.doConnect(mav, "preset", "5760");

                    try
                    {
                        mav.GetParam("SYSID_THISMAV");
                        mav.setParam("SYSID_THISMAV", a + 1, true);

                        mav.GetParam("FRAME_CLASS");
                        mav.setParam("FRAME_CLASS", 1, true);
                    }
                    catch
                    {
                    }

                    MainV2.Comports.Add(mav);
                }

                return;
            }
            catch
            {
                CustomMessageBox.Show(Strings.Failed_to_connect_to_SITL_instance, Strings.ERROR);
                return;
            }
        }
예제 #59
0
        private void Polyline_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Polyline polyline = sender as Polyline;
            LineInfo info     = (LineInfo)polyline.Tag;

            string[] ress = info.Info.Split('|');
            int      ss   = int.Parse(ress[0]);

            string[] fi = ress[1].Split(new char[] { '=', '+', '*', 'X' });
            double   b  = double.Parse(fi[1]);
            double   m  = double.Parse(fi[4]);
            double   c  = double.Parse(fi[5]);
            string   tt = "";

            switch (ss)
            {
            case 0: tt = "基本的函数:" + b + "X**" + m + "+" + c;
                break;

            case 1:
                tt = "Sin()函数:" + b + "Sin(X**" + m + ")+" + c;
                break;

            case 2:
                tt = "Cos()函数:" + b + "Cos(X**" + m + ")+" + c;;
                break;

            case 3:
                tt = "Tan()函数:" + b + "Tan(X**" + m + ")+" + c;;
                break;
            }
            switch (MyMessageBox.Show("是否删除此条函数线?\n" + tt, "提示", MyMessageBox.MyMessageBoxButton.ConfirmNOButton, "删除该曲线", "取消", "查找值"))
            {
            case MyMessageBox.MyMessageBoxResult.Comfirm:
                temp = info.Info;
                int x = Lines.FindIndex(pre);
                Lines.RemoveAt(x);
                temp = "";
                Draw();
                break;

            case MyMessageBox.MyMessageBoxResult.Buttons:
                InputBox inputBox = new InputBox();
                string   res      = inputBox.Show("请输入X的值:", "查找Y值");

                if (isNum(res) == true)
                {
                    double xv = double.Parse(res);

                    switch (ss)
                    {
                    case 0:
                        MessageBox.Show("当X=" + xv + "时\nY=" + (b * Math.Pow(xv, m) + c).ToString(), "结果");
                        break;

                    case 1:
                        MessageBox.Show("当X=" + xv + "时\nY=" + (b * Math.Sin(Math.Pow(xv, m)) + c).ToString(), "结果");
                        break;

                    case 2:
                        MessageBox.Show("当X=" + xv + "时\nY=" + (b * Math.Cos(Math.Pow(xv, m)) + c).ToString(), "结果");
                        break;

                    case 3:
                        MessageBox.Show("当X=" + xv + "时\nY=" + (b * Math.Tan(Math.Pow(xv, m)) + c).ToString(), "结果");
                        break;
                    }
                }
                else
                {
                    MessageBox.Show("输入错误", "错误");
                }
                break;
            }
        }
        private void btnAdd_Click(object sender, EventArgs e)
        {
            MultiTaskingRunner runner = new MultiTaskingRunner();

            InputBox box = new InputBox();
            box.ShowDialog();

            string modUrl = box.InputString;
            foreach (ConnectionHelper conn in Connections)
            {
                string name = Program.GlobalSchoolCache[conn.UID].Title;
                runner.AddTask(string.Format("{0}({1})", name, conn.UID), (x) =>
                {
                    object[] obj = x as object[];
                    ConnectionHelper c = obj[0] as ConnectionHelper;
                    string xurl = (string)obj[1];
                    AddDesktopModule(c, xurl);
                }, new object[] { conn, modUrl }, new System.Threading.CancellationTokenSource());
            }
            runner.ExecuteTasks();

            try
            {
                InitConnections();
                LoadAllModuleConfig();
                GroupByToDataGrid();
            }
            catch { Close(); } //爆了就關吧。
        }