private void NotifyChildren() { foreach (TerminalButton Tb in _terminalButtons) { Tb.AssignTerminalInputManager(this); } }
private void addControls(Point defaultSize) { // The description label this.lblDescription = new Lbl(this.Description, this); this.lblDescription.Size = new Size(this.Width - 20, this.lblDescription.Height + 1); // The size textboxes this.tbWidth = new Tb(this); this.tbWidth.Text = defaultSize.X.ToString(); this.tbWidth.Size = new Size(this.tbWidth.Width / 2, this.tbWidth.Height); this.tbHeight = new Tb(this); this.tbHeight.Text = defaultSize.Y.ToString(); this.tbHeight.Size = this.tbWidth.Size; // The Ok and Cancel buttons this.btnOk = new Btn("Ok", this); this.btnOk.Click += (o, e) => { int number; if (!int.TryParse(this.tbWidth.Text, out number) || !int.TryParse(this.tbHeight.Text, out number)) { MessageBox.Show("Please enter an integer value.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } this.DialogResult = DialogResult.OK; this.Close(); }; this.btnCancel = new Btn("Cancel", this); this.btnCancel.Click += (o, e) => { this.DialogResult = DialogResult.Cancel; this.Close(); }; }
public NumericUpDown() { InitializeComponent(); baseContainer.DataContext = this; // フォーカス更新時 IsKeyboardFocusWithinChanged += (sender, e) => { // DateTimePicker内の全てのコントロールからフォーカスが離れたら if ((bool)e.NewValue == false) { var value = Parse(this, Tb.Text, Format); if (value.HasValue) { Value = value.Value; } SetText(this); } }; // マウスホイール時 MouseWheel += (sender, e) => { if (!IsKeyboardFocusWithin) { return; } if (0 < e.Delta) { Value++; } else { Value--; } e.Handled = true; }; // テキストボックス.キー入力時 Enterキー押下したらフォーカスを移動する。 Tb.PreviewKeyDown += (sender, e) => { if (e.Key != Key.Enter) { return; } var shift = (Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift; // 次のフォーカスへ移動する。 Tb.MoveFocus(new TraversalRequest(shift ? FocusNavigationDirection.Previous : FocusNavigationDirection.Next)); // 次のフォーカスへENTERキーイベントを渡さない。 e.Handled = true; }; // テキストボックス フォーカス取得時に全選択する。 TextBoxSelectAllWhenGotFocusBehavior.SetIsEnabled(Tb, true); }
private void textBoxDoubleClick(object sender, EventArgs e) { Tb.Visible = true; ((Label)sender).Visible = false; Tb.SelectAll(); Tb.Focus(); }
public void DatabaseDeserializing() { Database DB = new Database(@"C:\Users\Moataz\Workspace\Software\Database Architect\Active Code\DatabaseArchitect\Southwind\Database.db.txt"); DB.Read(); foreach (Table Tb in DB.Tables) { Tb.ReadRecords(); } }
private void Button_del(object sender, RoutedEventArgs e) { int sim = Tb.Text.Length - 1; string text = Tb.Text; Tb.Clear(); for (int q = 0; q < sim; q++) { Tb.Text = Tb.Text + text[q]; } }
private void ShowBottom(object sender, RoutedEventArgs e) { ShowOrHidden(); var res = PositionHandler.Draw(Grid, typeof(Button), "Button", 50, 0, -50, 50, PositionDirectionEnum.Bottom); Tb.Width = 250; Tb.SetValue(Canvas.LeftProperty, res.Xy[0]); Tb.SetValue(Canvas.TopProperty, res.Xy[1]); Pg.Data = res.PathGeometry; Rg2.Rect = res.Rect; }
public void Invoke(CancellationToken cancellationToken) { var tedit = Tb.CreateEdit(); _dead.ForEach(x => x.Invoke(tedit)); if (cancellationToken.CanBeCanceled && cancellationToken.IsCancellationRequested) { tedit.Dispose(); } tedit.Apply(); }
private void updateThongSo() { dgvThongSo["giaTri", 0].Value = giaTocNenQuyDoiagr1.ToString(); dgvThongSo["giaTri", 1].Value = Math.Round(giaTocNenThamChieuagr, 4).ToString(); dgvThongSo["giaTri", 2].Value = hsQuanTrongg1.ToString(); dgvThongSo["giaTri", 3].Value = Math.Round(giaTocNenTKag, 4).ToString(); dgvThongSo["giaTri", 4].Value = S.ToString(); dgvThongSo["giaTri", 5].Value = Tb.ToString(); dgvThongSo["giaTri", 6].Value = Tc.ToString(); dgvThongSo["giaTri", 7].Value = Td.ToString(); dgvThongSo["giaTri", 8].Value = hsUngXuq.ToString(); KlDongDat(); }
private async void StartTextAsync(String[] data) { for (int i = 0; i < data.Length; i++) { Tb.BeginAnimation(OpacityProperty, new DoubleAnimation(0, 1, TimeSpan.FromSeconds(1.2))); Tb.Text = data[i]; if (i != data.Length - 1) { await Task.Delay(3000); Tb.BeginAnimation(OpacityProperty, new DoubleAnimation(1, 0, TimeSpan.FromSeconds(1.5))); await Task.Delay(1500); } } }
private void Button_division(object sender, RoutedEventArgs e) { if (Tb.Text == "") { return; } else if (x != 0) { Col(); la.Content = y.ToString() + "/"; Tb.Clear(); x = y; action = 4; } else { x = float.Parse(Tb.Text); Tb.Clear(); action = 4; la.Content = x.ToString() + "/"; } }
protected override void AddInterfaces() { base.AddInterfaces(); Tb.AddInterfaceImplementation(typeof(IReadonlyConfiguration)); }
private void Window_Loaded(object sender, RoutedEventArgs e) { Tb.Focus(); Tb.SelectAll(); Keyboard.Focus(Tb); }
//protected void btnSubmit_Click(object sender, EventArgs e) public void process() { try { //if (txtStartDate.Text.Trim() == "" || txtTime.Text.Trim() == "") //{ // WebMsgBox.Show("Please enter Start Date and Time", this.Page); // return; //} //string StartDate = txtStartDate.Text.Trim(); //string time = txtTime.Text.Trim(); ArrayList tbName = new ArrayList(); //tbName.Add("A50001"); tbName.Add("ADDMAST-1"); //tbName.Add("AGENTMAST"); tbName.Add("ALLVCR-2"); //tbName.Add("ALOGIN"); tbName.Add("AVS_ACC-3"); tbName.Add("AVS_DDS-4"); // tbName.Add("AVS_DDS_LOCK"); //tbName.Add("AVS_DDSHISTORY"); tbName.Add("Avs_FreezAccDetails-5"); //tbName.Add("AVS_InvAccountMaster"); //tbName.Add("AVS_InvDepositeMaster"); //tbName.Add("AVS_InvParameter"); //tbName.Add("AVS_LienMarkDetails"); //tbName.Add("AVS_LnTrx"); //tbName.Add("Avs_Notice_Chrg"); //tbName.Add("AVS_SHRALLOTMENT"); //tbName.Add("AVS_SHRAPP"); //tbName.Add("AVS1000"); //tbName.Add("DEPOSITGL"); tbName.Add("DEPOSITINFO-6"); tbName.Add("LoanInfo-7"); //tbName.Add("GLMAST"); //tbName.Add("ImageMaster"); //tbName.Add("ImageRelation"); //tbName.Add("INTERESTMASTER"); //tbName.Add("INTRESTMASTER"); //tbName.Add("LIEN_MARK"); //tbName.Add("LOANSCHEDULE"); tbName.Add("MASTER-8"); //tbName.Add("MEMSTAT"); tbName.Add("SHARESINFO-9"); //EntryDate = EntryDate; string StartDate1 = conn.ConvertDate(EntryDate).ToString(); System.Collections.Generic.List <System.Web.UI.WebControls.ListItem> files = new System.Collections.Generic.List <System.Web.UI.WebControls.ListItem>(); if (!Directory.Exists(@"C:\Backup")) { Directory.CreateDirectory(@"C:\Backup"); } SqlConnection Conn = new SqlConnection(conn.DbName()); try { foreach (string Tb in tbName) { DataTable dt = new DataTable(); DataTable dt1 = new DataTable(); string[] Tbn = Tb.Split('-'); string tbname = Tbn[0].ToString(); SqlDataAdapter sda = new SqlDataAdapter("ISP_AVS0179", Conn); sda.SelectCommand.CommandType = CommandType.StoredProcedure; sda.SelectCommand.Parameters.Add("@Flag", SqlDbType.NVarChar).Value = tbname; sda.SelectCommand.Parameters.Add("@StartDate", SqlDbType.DateTime).Value = StartDate1; sda.Fill(dt); SqlDataAdapter sda1 = new SqlDataAdapter("ISP_AVS0180", Conn); sda1.SelectCommand.CommandType = CommandType.StoredProcedure; sda1.SelectCommand.Parameters.Add("@Flag", SqlDbType.NVarChar).Value = tbname; sda1.Fill(dt1); string[] typeArr = dt1.Rows.OfType <DataRow>().Select(k => k[1].ToString()).ToArray(); string fileName = Tbn[1] + "-" + DateTime.Now.Date.ToShortDateString() + DateTime.Now.ToShortTimeString(); fileName = fileName.Replace("/", ""); fileName = fileName.Replace("AM", ""); fileName = fileName.Replace("PM", ""); fileName = fileName.Replace(" ", ""); fileName = fileName.Replace(":", ""); if (dt.Rows.Count > 0) { try { StreamWriter sw; using (sw = File.CreateText(@"C:\Backup\" + fileName + ".txt")) { string type; int i; int j = 0; sw.Write("Insert Into " + Tb + " ("); for (i = 0; i < dt.Columns.Count; i++) { if (i != dt.Columns.Count - 1) { sw.Write(dt.Columns[i].ColumnName + ","); } else { sw.Write(dt.Columns[i].ColumnName); } } sw.Write(") \r\n Values "); foreach (DataRow row in dt.Rows) { int RowCount = dt.Rows.Count; j += 1; sw.Write("("); object[] array = row.ItemArray; string value = string.Empty; for (i = 0; i < array.Length; i++) { type = typeArr[i]; if (type == "float" || type == "bigint" || type == "numeric" || type == "int") { value = array[i].ToString(); if (value.Trim() == "") { value = "null"; } sw.Write(value); } else if (type == "nvarchar" || type == "varchar") { sw.Write("'" + array[i].ToString() + "'"); } else if (type == "datetime2" || type == "datetime") { string date = array[i].ToString(); if (date != "") { if (date.Contains("-")) { string[] ab = date.Split('-'); string chk = ab[0]; if (chk.Length > 2) { } else { string date1 = ab[2]; string date2 = date1.Substring(0, 4); date1 = date1.Substring(4); date = date2 + "-" + ab[1] + "-" + ab[0] + " " + date1; } } else if (date.Contains("/")) { string[] ab = date.Split('/'); string chk = ab[0]; if (chk.Length > 2) { } else { string date1 = ab[2]; string date2 = date1.Substring(0, 4); date1 = date1.Substring(4); date = date2 + "-" + ab[1] + "-" + ab[0] + " " + date1; } } } sw.Write("'" + date + "'"); } else { sw.Write(array[i].ToString()); } if (i != array.Length - 1) { sw.Write(","); } } if (j == RowCount) { sw.Write(") \r\n"); } else { sw.Write("), \r\n"); } } } //StringBuilder SBTxt = new StringBuilder(); //SBTxt.Append(sw.ToString()); //StringBuilder SBTxt1 = new StringBuilder(); //SBTxt1.Append(encrypt(SBTxt.ToString())); //sw.Close(); StreamReader sr = new StreamReader(@"C:\Backup\" + fileName + ".txt"); StringBuilder SBTxt = new StringBuilder(); SBTxt.Append(sr.ReadToEnd().ToString()); StringBuilder SBTxt1 = new StringBuilder(); // SBTxt1.Append(SBTxt.ToString()); SBTxt1.Append(encrypt(SBTxt.ToString())); sr.Close(); var fs = new FileStream(@"C:\Backup\" + fileName + ".txt", FileMode.Truncate); fs.Close(); StreamWriter sw1; using (sw1 = File.CreateText(@"C:\Backup\" + fileName + ".txt")) { sw1.Write(SBTxt1.ToString()); } sw1.Close(); files.Add(new System.Web.UI.WebControls.ListItem(@"C:\Backup\" + fileName + ".txt")); } catch (Exception Ex) { ExceptionLogging.SendErrorToText(Ex); } //StreamReader sr1 = new StreamReader(@"D:\MyDir\" + fileName + ".txt"); //StringBuilder SBTxt2 = new StringBuilder(); //SBTxt2.Append(sr1.ReadToEnd().ToString()); //StringBuilder SBTxt3 = new StringBuilder(); //SBTxt3.Append(Decrypt(SBTxt2.ToString())); //sr1.Close(); //Response.Clear(); //Response.ClearContent(); //Response.ClearHeaders(); //Response.Buffer = true; //Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".txt"); //Response.Charset = ""; //Response.ContentType = "application/octet-stream"; //using (StringWriter writer = new StringWriter()) //{ // writer.WriteLine(SBTxt1); // writer.Close(); // Response.Output.Write(writer); //} //HttpContext.Current.Response.Flush(); //HttpContext.Current.Response.SuppressContent = true; //HttpContext.Current.ApplicationInstance.CompleteRequest(); //using (sw = File.CreateText(@"D:\MyDir\" + fileName + "Decrypt.txt")) //{ // sw.Write(SBTxt3.ToString()); //} //sw.Close(); } } using (ZipFile zip = new ZipFile()) { zip.AlternateEncodingUsage = ZipOption.AsNecessary; //zip.AddDirectoryByName("Files"); foreach (System.Web.UI.WebControls.ListItem li in files) { zip.AddFile(li.Value, "Your Files"); } Response.Clear(); Response.BufferOutput = false; string zipName = String.Format("Backup_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss")); Response.ContentType = "application/zip"; Response.AddHeader("content-disposition", "attachment; filename=" + zipName); zip.Save(Response.OutputStream); //WebMsgBox.Show("BACKUP Successful", this.Page); Response.End(); } //WebMsgBox.Show("BACKUP Successful", this.Page); } catch (Exception Ex) { ExceptionLogging.SendErrorToText(Ex); //WebMsgBox.Show("Error while BACKUP", this.Page); } finally { Conn.Close(); } } catch (Exception Ex) { ExceptionLogging.SendErrorToText(Ex); } }
/* public static void PrintInOrder(BinTreeNode<string> t) * { * if (t != null) * { * PrintInOrder(t.GetLeft()); * Console.Write(t.GetInfo().ToString() + ""); * PrintInOrder(t.GetRight()); * } * * }*/ // ט. כניסה: הפונקצייה מקבלת ביטוי אלגברי הכולל משתנה איקס ו-ואי, ושתי מספרים ממשיים //ט. יציאה: הפונקצייה מחזירה את תוצאת הביטוי בהצבת המספרים הממשיים ב איקס, וואי בהתאמה public static double BracketReader(String str1, double x, double y) { int Cb = 0; int Ob = 0; string Bb = null; string Ab = null; string Ib = null; double Tb; for (int i = str1.Length - 1; i >= 0; i--) { if (str1[i] == 'x') { int n; if (i > 0 && (int.TryParse(str1[i - 1].ToString(), out n) || str1[i - 1] == 'y' || str1[i - 1] == 'x')) // 6x or 6-x checking, Replacing 6x to 6*x { Bb = str1.Substring(0, i) + '*'; } else { Bb = str1.Substring(0, i); } Ib = x.ToString(); Ab = str1.Substring(i + 1, str1.Length - i - 1); str1 = Bb + Ib + Ab; } if (str1[i] == 'y') { int n; if (i > 0 && (int.TryParse(str1[i - 1].ToString(), out n) || str1[i - 1] == 'y' || str1[i - 1] == 'x')) // 6x or 6-x checking, Replacing 6x to 6*x { Bb = str1.Substring(0, i) + '*'; } else { Bb = str1.Substring(0, i); } Ib = y.ToString(); Ab = str1.Substring(i + 1, str1.Length - i - 1); str1 = Bb + Ib + Ab; } } for (int i = str1.Length - 1; i >= 0; i--) { if (str1[i] == ')') { Cb = i; //getting the last ')' } if (str1[i] == '(') { Ab = str1.Substring(Cb + 1, str1.Length - Cb - 1); // same with sqrt and unsqrt. the after will be the same Ob = i; //same Ib = str1.Substring(Ob + 1, Cb - Ob - 1); if (str1[i] == '(' && i != 0 && str1[i - 1] == 't') // if the brackets is part of the sqrt { Bb = str1.Substring(0, Ob - 4); // the -1 will delete the 's' from the sentence Tb = Math.Sqrt(CalculateTreeOfParser(BuildTreeOfParser(Ib))); } else if (str1[i] == '(' && i != 0 && str1[i - 1] == 'n') // if the brackets is part of the sqrt { Bb = str1.Substring(0, Ob - 3); // the -1 will delete the 's' from the sentence Tb = Math.Sin(CalculateTreeOfParser(BuildTreeOfParser(Ib))); } else if (str1[i] == '(' && i != 0 && str1[i - 1] == 's' && str1[i - 2] == 'o') // if the brackets is part of the sqrt { Bb = str1.Substring(0, Ob - 3); // the -1 will delete the 's' from the sentence Tb = Math.Cos(CalculateTreeOfParser(BuildTreeOfParser(Ib))); } else if (str1[i] == '(' && i != 0 && str1[i - 1] == 's' && str1[i - 2] == 'b') // if the brackets is part of the abs { Bb = str1.Substring(0, Ob - 3); // the -1 will delete the 's' from the sentence Tb = Math.Abs(CalculateTreeOfParser(BuildTreeOfParser(Ib))); } else // if the brackets is only brackets and not part of any sqrt { Bb = str1.Substring(0, Ob); // there is no 's' to delete Tb = CalculateTreeOfParser(BuildTreeOfParser(Ib)); } str1 = Bb + Tb.ToString() + Ab; // same with sqrt and unsqrt i = str1.Length; // same with sqrt and unsqrt } } return(CalculateTreeOfParser(BuildTreeOfParser(str1))); }
protected virtual void AddRealtimeImplementation() => Tb.AddInterfaceImplementation(typeof(IRealtimeConfiguration));
private void Tb_Click(object sender, EventArgs e) { Tb form2 = new Tb(); form2.Show(); }
/// <summary> /// Scroll textbox to the bookmark /// </summary> public virtual void DoVisible() { Tb.Selection.Start = new Place(0, LineIndex); Tb.DoRangeVisible(Tb.Selection, true); Tb.Invalidate(); }
/// <summary> /// 修改表格样式 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TableFormat_Click(object sender, RibbonControlEventArgs e) { //弹出窗体提示 DialogResult IsWait = MessageBox.Show("如果表格较多运行较为缓慢,进度可在Word左下角查看" + Environment.NewLine + "是否继续?", "请选择", MessageBoxButtons.YesNo); if (IsWait != DialogResult.Yes) { return; } WordApp = Globals.ThisAddIn.Application; WordDoc = WordApp.ActiveDocument; WordApp.ScreenUpdating = false; //关闭屏幕刷新 #region //读取配置文件 //读取配置文件 ClsThisAddinConfig clsConfig = new ClsThisAddinConfig(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments)); //表格间距 bool SpaceGroupCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "SpaceGroupCheck", true); //首行缩进 bool TableIndentCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "TableIndentCheck", true); //段前 decimal TableBeforeMainBody = clsConfig.ReadConfig <decimal>("SettingFormatForm", "TableBeforeMainBody", 0m); //段后 decimal TableAfterMainBody = clsConfig.ReadConfig <decimal>("SettingFormatForm", "TableAfterMainBody", 0m); //行间距 decimal TableRowSpace = FormatFunC.RowSpace(clsConfig.ReadConfig <string>("SettingFormatForm", "TableRowSpace", "单倍行距")); //表格边框 bool BorderGroupCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "BorderGroupCheck", true); //上下边框宽度1磅 bool TableTBBorderCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "TableTBBorderCheck", true); //左右无边框 bool TableLRBorderCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "TableLRBorderCheck", true); //表格其他选项 bool OtherGroupCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "OtherGroupCheck", true); //垂直居中 bool TableVerticalCenterCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "TableVerticalCenterCheck", true); //标题及合计行加粗 bool TableTitleWiderCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "TableTitleWiderCheck", true); //表格字号 decimal TableFontSize = FormatFunC.FontSize(clsConfig.ReadConfig <string>("SettingFormatForm", "TableFontSize", "小四")); #endregion if (SpaceGroupCheck || BorderGroupCheck || OtherGroupCheck) { //在状态栏显示进度 WordApp.StatusBar = "当前进度:0%"; int i3 = WordDoc.Tables.Count; int i4 = 1; foreach (Word.Table Tb in WordDoc.Tables) { Tb.Select(); //间距 if (SpaceGroupCheck) { if (TableIndentCheck) { WordApp.Selection.ParagraphFormat.CharacterUnitLeftIndent = 0; WordApp.Selection.ParagraphFormat.CharacterUnitRightIndent = 0; WordApp.Selection.ParagraphFormat.CharacterUnitFirstLineIndent = 0; WordApp.Selection.ParagraphFormat.FirstLineIndent = WordApp.CentimetersToPoints(0); } WordApp.Selection.ParagraphFormat.SpaceBefore = 0; WordApp.Selection.ParagraphFormat.LineUnitBefore = float.Parse(TableBeforeMainBody.ToString()); WordApp.Selection.ParagraphFormat.SpaceAfter = 0; WordApp.Selection.ParagraphFormat.LineUnitAfter = float.Parse(TableAfterMainBody.ToString()); WordApp.Selection.ParagraphFormat.LineSpacing = WordApp.LinesToPoints(float.Parse(TableRowSpace.ToString())); WordApp.Selection.ParagraphFormat.DisableLineHeightGrid = -1; //行距设置中,不勾选“如果定义了文档网格,则于网格对齐” WordApp.Selection.ParagraphFormat.AutoAdjustRightIndent = -1; //行距设置中,不勾选“如果定义了文档网格,则自动调整右缩进” } //边框 if (BorderGroupCheck) { //上下边框1磅 if (TableTBBorderCheck) { Tb.Borders[Word.WdBorderType.wdBorderTop].LineStyle = Word.WdLineStyle.wdLineStyleSingle; Tb.Borders[Word.WdBorderType.wdBorderTop].LineWidth = Word.WdLineWidth.wdLineWidth100pt; Tb.Borders[Word.WdBorderType.wdBorderTop].Color = Word.WdColor.wdColorAutomatic; Tb.Borders[Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleSingle; Tb.Borders[Word.WdBorderType.wdBorderBottom].LineWidth = Word.WdLineWidth.wdLineWidth100pt; Tb.Borders[Word.WdBorderType.wdBorderBottom].Color = Word.WdColor.wdColorAutomatic; } //左右无边框 if (TableLRBorderCheck) { Tb.Borders[Word.WdBorderType.wdBorderLeft].LineStyle = Word.WdLineStyle.wdLineStyleNone; Tb.Borders[Word.WdBorderType.wdBorderRight].LineStyle = Word.WdLineStyle.wdLineStyleNone; } } //其他选项 if (OtherGroupCheck) { //垂直居中 if (TableVerticalCenterCheck) { WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; } // if (TableTitleWiderCheck) { } //表格字体 Tb.Range.Font.Size = float.Parse(TableFontSize.ToString()); } //显示进度 WordApp.StatusBar = "当前进度:" + Math.Round((i4 * 100d / i3), 2) + "%"; i4++; } } WordApp.ScreenUpdating = true;//关闭屏幕刷新 }
protected virtual void AddInpcImplementation() { // todo: refactor this method? Tb.AddInterfaceImplementation(typeof(INotifyPropertyChanged)); Tb.AddInterfaceImplementation(typeof(INotifyingConfiguration)); var field = Tb.DefineField( "PropertyChanged", typeof(PropertyChangedEventHandler), FieldAttributes.Private); var eventInfo = Tb.DefineEvent( "PropertyChanged", EventAttributes.None, typeof(PropertyChangedEventHandler)); { var ibaseMethod = typeof(INotifyPropertyChanged).GetMethod("add_PropertyChanged"); Debug.Assert(ibaseMethod != null, nameof(ibaseMethod) + " != null"); var addMethod = Tb.DefineMethod("add_PropertyChanged", ibaseMethod.Attributes ^ MethodAttributes.Abstract, ibaseMethod.CallingConvention, ibaseMethod.ReturnType, new[] { typeof(PropertyChangedEventHandler) }); var combine = typeof(Delegate).GetMethod("Combine", new[] { typeof(Delegate), typeof(Delegate) }); Debug.Assert(combine != null, nameof(combine) + " != null"); var generator = addMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldfld, field); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Call, combine); generator.Emit(OpCodes.Castclass, typeof(PropertyChangedEventHandler)); generator.Emit(OpCodes.Stfld, field); generator.Emit(OpCodes.Ret); eventInfo.SetAddOnMethod(addMethod); } { var ibaseMethod = typeof(INotifyPropertyChanged).GetMethod("remove_PropertyChanged"); Debug.Assert(ibaseMethod != null, nameof(ibaseMethod) + " != null"); var removeMethod = Tb.DefineMethod("remove_PropertyChanged", ibaseMethod.Attributes ^ MethodAttributes.Abstract, ibaseMethod.CallingConvention, ibaseMethod.ReturnType, new[] { typeof(PropertyChangedEventHandler) }); var remove = typeof(Delegate).GetMethod("Remove", new[] { typeof(Delegate), typeof(Delegate) }); Debug.Assert(remove != null, nameof(remove) + " != null"); var generator = removeMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldfld, field); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Call, remove); generator.Emit(OpCodes.Castclass, typeof(PropertyChangedEventHandler)); generator.Emit(OpCodes.Stfld, field); generator.Emit(OpCodes.Ret); eventInfo.SetRemoveOnMethod(removeMethod); } { var methodBuilder = Tb.DefineMethod("OnPropertyChanged", MethodAttributes.Family | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot, CallingConventions.HasThis, typeof(void), new[] { typeof(string) }); var generator = methodBuilder.GetILGenerator(); var returnLabel = generator.DefineLabel(); generator.DeclareLocal(typeof(PropertyChangedEventHandler)); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldfld, field); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Call, typeof(PropertyChangedInvoker).GetMethod("Invoke")); generator.MarkLabel(returnLabel); generator.Emit(OpCodes.Ret); eventInfo.SetRaiseMethod(methodBuilder); _onPropertyChangedMethod = methodBuilder.GetBaseDefinition(); } }