winform小技巧

上传人:re****.1 文档编号:573815980 上传时间:2024-08-15 格式:PDF 页数:15 大小:130.86KB
返回 下载 相关 举报
winform小技巧_第1页
第1页 / 共15页
winform小技巧_第2页
第2页 / 共15页
winform小技巧_第3页
第3页 / 共15页
winform小技巧_第4页
第4页 / 共15页
winform小技巧_第5页
第5页 / 共15页
点击查看更多>>
资源描述

《winform小技巧》由会员分享,可在线阅读,更多相关《winform小技巧(15页珍藏版)》请在金锄头文库上搜索。

1、一,通常我们做软件时,如果想点击退出时,真正实现退出。要么就用Application.Exit,但还是会有些线程可能并未能及时关闭,或者程序因为开的线程太多而无法及时退出。这时候使用结束进程能解决这些问题 /退出方法 private void db_logoff_Click(object sender, System.EventArgs e) FormClose = true; System.Diagnostics.Process myProcesses; myProcesses = System.Diagnostics.Process.GetProcessesByName(StudentSy

2、stem); foreach (System.Diagnostics.Process myProcess in myProcesses) myProcess.Kill(); Application.Exit(); this.Close(); /退出 二,托盘是软件比较常用的功能,在关闭窗体之前加上如下代码,看起来更像一个软件了 if (!FormClose) e.Cancel = true; WindowState = FormWindowState.Minimized; this.Hide(); this.notifyIcon1.ShowBalloonTip(0x2710, 系统托盘提示 ,

3、 程序已最小化到托盘 , 右键点击显示菜单,双击显示窗体。, ToolTipIcon.Info);/托盘图标加载时提示 ; 三,更换皮肤。曾用过DotNetBar 控件, 里面的 CorlorPickerDropDown功能还行,可以随意变换皮肤,并且有预览效果,用起来会为软件增色不少。 #region 皮肤更换 private void ddl_colChose_SelectedColorChanged(object sender, EventArgs e) m_ColorSelected = true; / Indicate that color was selected for butt

4、onStyleCustom_ExpandChange method RibbonPredefinedColorSchemes.ChangeOffice2007ColorTable(m_BaseColorScheme, ddl_colChose.SelectedColor); private void ddl_colChose_ExpandChange(object sender, EventArgs e) if (ddl_colChose.Expanded) / Remember the starting color scheme to apply if no color is selecte

5、d during live-preview m_ColorSelected = false; m_BaseColorScheme = (Office2007Renderer)GlobalManager.Renderer).ColorTable.InitialColorScheme; else if (!m_ColorSelected) RibbonPredefinedColorSchemes.ChangeOffice2007ColorTable(m_BaseColorScheme); private void ddl_colChose_ColorPreview(object sender, C

6、olorPreviewEventArgs e) RibbonPredefinedColorSchemes.ChangeOffice2007ColorTable(m_BaseColorScheme, e.Color); #endregion 四、获取资源文件(Xml)- 要在同一命名空间下获取 XmlDocument myXml = new XmlDocument(); string fileName = AdminClient.Resources.bpmsCodes.xml; Assembly asm = Assembly.GetExecutingAssembly();/读取嵌入式资源 Str

7、eam strm = asm.GetManifestResourceStream(fileName); myXml.Load(strm);/读取指定的 XML 文档WinForm 的RadioButton 使用小技巧当多个 RadioButton 同在一个容器里面的时候,多半的操作都是要得到其中一个的值这个时候我们就没有必要去为每一个RadioButton 写一个 CheckedChange事件,这样会写很多代码,太累了。这个时候我们就可以借住委托来添加一个新的事件,用新的事件代替所有RadioButton 的CheckedChange 事件。我要实现的要求就是:当选择中任意一个RadioBu

8、tton的时候 Label17 就变成我选择的RadioButton 的Text 值新事件代码如下:/RadioButton 新事件public void radioBtn_CheckedChange(object sender, EventArgs e) if (!(RadioButton)sender).Checked) return; string rechargeMoney = string.Empty; switch (RadioButton)sender).Text.ToString() case10 : rechargeMoney = 10 ; this.lbl_money_ti

9、p.Text = rechargeMoney; break; case20 : rechargeMoney = 20 ; this.lbl_money_tip.Text = rechargeMoney; break; case30 : rechargeMoney = 30 ; this.lbl_money_tip.Text = rechargeMoney; break; case40 : rechargeMoney = 40 ; this.lbl_money_tip.Text = rechargeMoney; break; case50 : rechargeMoney = 50 ; this.

10、lbl_money_tip.Text = rechargeMoney; break; case100 : rechargeMoney = 100 ; this.lbl_money_tip.Text = rechargeMoney; break; default: break; 如何使用这个事件呢?有两种方法1、在VS2008 中依次选中每一个RadioButton 右击- “ 属性 ” 在属性中找到 CheckedChange事件,为其指定为新写的事件。如下图:2、在初始化窗体的时候添加如下代码:public StartPage() InitializeComponent(); this.ra

11、dio_Money_10.CheckedChanged += newEventHandler(this.radioBtn_CheckedChange); this.radio_Money_20.CheckedChanged += newEventHandler(this.radioBtn_CheckedChange); this.radio_Money_30.CheckedChanged += newEventHandler(this.radioBtn_CheckedChange); this.radio_Money_40.CheckedChanged += newEventHandler(t

12、his.radioBtn_CheckedChange); this.radio_Money_50.CheckedChanged += newEventHandler(this.radioBtn_CheckedChange); this.radio_Money_100.CheckedChanged += newEventHandler(this.radioBtn_CheckedChange); 到此这个简单的方法就完成了,让我少写了不少的垃圾代码;可以举一反三。比如复选框被选中,传出去一个值等等。这也让我对委托有了更清晰了理解。屏蔽窗体关闭按钮DllImport(USER32.DLL) priv

13、ate static extern IntPtr GetSystemMenu(IntPtr hWnd, UInt32 bRevert); DllImport(USER32.DLL) private static extern UInt32 RemoveMenu(IntPtr hMenu, UInt32 nPosition, UInt32 wFlags); private const UInt32 SC_CLOSE = 0x0000F060; private const UInt32 MF_BYCOMMAND = 0x00000000; public Form1() InitializeComp

14、onent(); IntPtr hMenu = GetSystemMenu(this.Handle, 0); RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND); Winform 小技巧未添加 ( 静态 ) 的成员为实例成员获取程序可执行文件的路径:System.Reflection.Assembly.GetEntryAssembly().Location 获取程序所在文件夹的路径:System.Environment.CurrentDirectory 获取 Windows 系统特殊文件夹的路径:System.Environment.GetFolderPath(

15、 Environment.SpecialFolder folder ) 获取鼠标的屏幕坐标:System.Windows.Forms.Control.MousePosition(静态 ) 屏幕坐标转换为工作区坐标:System.Windows.Forms.Control.PointToClient(Point p) 获取程序集中的资源:System.Resources.ResourceManager 类控件和对象属性双向绑定:对象实需现接口System.ComponentModel.INotifyPropertyChanged接口向活动应用程序发送击键:System.Windows.Forms

16、.SendKeys.Send (string keys)(静态 ) 窗体显示后改变窗体的位置: 1. 修改 Form.StartPosition 为System.Windows.Forms.FormStartPosition.Manual 2. 修改 Form.Location 查看窗体样式:利用VS 自带工具 spy+ 窗体显示在另一窗体之上:Form1.Owner = Form2。这样 Form1就显示在 Form2上,并随 Form2一起关闭和最小化。闪烁窗体:调用 ApiFlashWindow DllImport(user32.dll) private static extern bo

17、ol FlashWindow(IntPtr hwnd, bool bInvert); public static void FlashWindow(System.Windows.Forms.Form window) FlashWindow(window.Handle, true); 窗体没有焦点也触发按键事件:Form.KeyPreview 设置为 true ,窗体将接受所有控件的按键事件。要仅在窗体级别处理键盘事件并且不允许控件接收键盘事件,请将窗体的 KeyPress 事件处理程序中的KeyPressEventArgs.Handled 属性设置为 true 。窗体全屏:form.Windo

18、wState = FormWindowState.Normal; Rectangle rect = Screen.PrimaryScreen.Bounds; form.Location = rect.Location; form.Size =rect.Size; 注意:全屏后如何恢复到之前状态。在资源管理器中打开文件夹的父文件夹并使该文件夹处于选中状态:System.Diagnostics.Process.Start(explorer.exe, dirPath); 在资源管理器中打开文件的文件夹并使该文件处于选中状态:System.Diagnostics.Process.Start(explo

19、rer.exe, /select, + filePath); 关闭窗体但不出发FormClosing 事件:调用 Form.Dispose() 方法关闭窗体在主窗体之前显示窗体: static void Main() Form frmMain=new Form(); Form frmLgn=new Form(); frmLgn.ShowDialog(); Application.Run( frmMain ); 使控件不显示聚焦框:如果控件有 ShowFocusCues 属性则可以通过覆写该属性实现。protected override bool ShowFocusCues get / 不显示聚

20、焦框 return false; 过滤 Windows 消息: System.Windows.Forms.IMessageFilter NotifyIcon不显示:设置 NotifyIcon.Ico属性PropertyGrid禁止编辑:在PropertyGrid的ValueChanged事件中添加如下代码private void propertyGrid1_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) e.ChangedItem.PropertyDescriptor.SetValue(this.propertyG

21、rid1.SelectedObject, e.OldValue); 使窗体不显示标题:重写 CreateParams属性, WS_CAPTION是一个常量。private const int WS_CAPTION = 0XC00000; protected override CreateParams CreateParams get CreateParams createParams; createParams = base.CreateParams; createParams.Style = WS_CAPTION; return createParams; 移动无标题栏窗体在窗体的 mous

22、emove 事件中处理 , 不能放进 mousedown 中,否则会无法接受鼠标双击消息Form_MouseMove() ReleaseCapture(); SendMessage(this.FindForm().Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0); DllImport(user32.dll) private static extern bool ReleaseCapture(); DllImport(user32.dll) private static extern bool SendMessage(IntPtr hwnd, int

23、wMsg, int wParam, int lParam); private const int WM_SYSCOMMAND = 0x0112; private const int SC_MOVE = 0xF010; private const int HTCAPTION = 0x0002; 强制重新绘制窗体及其内容的两种方法:1. 将 Invalidate 方法的重载之一与 Update 方法一起使用。2调用 Refresh 方法,此方法强制控件重新绘制其自身及其所有子级。这等效于将Invalidate 方法设置为 true 并将该方法与 Update 一起使用。Invalidate 方法控

24、制绘制或重新绘制的内容。Update 方法控制发生绘制或重新绘制的时间。如果将 Invalidate 和 Update 方法一起使用,而不是调用 Refresh ,则重新绘制的内容取决于您使用的 Invalidate 的重载。 Update 方法仅仅是强制立即绘制控件,而Invalidate 方法则控制当您调用 Update 方法时所绘制的内容。自己绘制树节点:设置 TreeView.DrawNode属性为 OwnerDrawText或OwnerDrawAll ,在TreeViewDrawNode。在TreeView.DrawNode 事件中进行绘制。 只有当节点可见时才绘制,否则可能会在 T

25、reeView左上角绘制不可见的节点,使显示出现问题。private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e) if (e.Node.IsVisible)/判断节点是否可见 if (e.State = 0) / 在这里添加未选中节点绘制代码,节点在未选中状态下State 为0,System.Windows.Forms.TreeNodeStates枚举中并不包括0, else / 其他状态的绘制代码 在IE 进程中打开网页:仅对 IE6有效/ 在框架 kaka 中打开 bing ,这时会打开 IE,并显示网页

26、http:/ / 打开百度也指定同一个框架kaka ,就会更改已打开的IE 的Uri 为百度。WebBrowser.Navigate(http:/,kaka,); 创建窗体大小的画布:重绘窗体边框需要创建和窗体一样大的画布。以下是重载 OnPaintBackground 方法,在绘制背景时绘制边框protected override void OnPaintBackground(PaintEventArgs e) IntPtr windowDC = GetWindowDC(this.Handle); try using (Graphics graphics = Graphics.FromHdc

27、(windowDC) / 绘制边框 finally ReleaseDC(this.Handle, windowDC); DllImport(user32.dll) public static extern IntPtr GetWindowDC(IntPtr hWnd); DllImport(user32.dll) public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); private const int WM_SYSCOMMAND = 0x0112; private const int SC_MOVE = 0xF010; pri

28、vate const int HTCAPTION = 0x0002; 为窗体和控件设置双缓冲:对于大多数应用程序,.NET Framework 提供的默认双缓冲将提供最佳效果。默认情况下,标准 Windows 窗体控件是双缓冲的。可以通过两种方法对窗体和所创作的控件启用默认双缓冲。一种方法是将 DoubleBuffered 属性设置为 true , 另一种方法是通过调用 SetStyle 方法将 OptimizedDoubleBuffer 标志设置为 true 。两种方法都将为窗体或控件启用默认双缓冲并提供无闪烁的图形呈现。建议仅对已为其编写所有呈现代码的自定义控件调用SetStyle 方法。

29、手动呈现双缓冲:参考以下类型BufferedGraphics BufferedGraphicsContext BufferedGraphicsManager 生成字符串的哈希编码:System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFiles(string content,string format) 获取配置文件的路径:AppDomain.CurrentDomain.SetupInformation.ConfigurationFile1. 如何创建一个可改变大小没有标题栏的窗体?(How to creat

30、e a form with resizing borders and no title bar?)form1.Text = string. Empty; form1.ControlBox = false; 2. 如何在 .NET的Windows窗体上启用 XP 主题集?(How to use XP Themes with Windows Forms using the .NET?)确认你的控件中 FlatStyle属性已经修改为System,再修改 Main方法。static void Main() Application.EnableVisualStyles(); Application.D

31、oEvents(); Application. Run(new Form1(); 3. 如何为一个窗体设置一个默认按钮?(How to set the default button for a form?)form1.AcceptButton = button1; 4. 如何为一个窗体设置一个取消按钮?(How to set the Cancel button for a form?)form1.CancelButton = button1; 5. 如何阻止一个窗体标题显示在任务栏上?(How to prevent a form from being shown in the taskbar?

32、)设置窗体的 ShowIntaskbar 属性为 False 6. 如何用现有可用字体绑定到ComboBox 控件?( How to fill a ComboBox with the available fonts?)comboBox1.Items.AddRange (FontFamily.Families); 7. 如何禁止 TextBox 控件默认的邮件菜单?(How to disable the default ContextMenu of a TextBox? )textBox1.ContextMenu = new ContextMenu (); 8. 如何获取 “ 我的文档 ” 等一

33、些系统文件夹路径? (How to get the path for My Documents and other system folders?)Environment.SpecialFolder中包含了一些系统文件夹信息MessageBox.Show(Environment.GetFolderPath( Environment.SpecialFolder.Personal ); 9. 如何获取应用程序当前执行的路径?(How to get the path to my running EXE?)string appPath = Application.ExecutablePath; 10.

34、 如何确定当前运行的系统? (How to determine which operating system is running? )OperatingSystem os = Environment.OSVersion; MessageBox.Show(os.Version.ToString(); MessageBox.Show(os.Platform.ToString(); 11. 如何从完整的路径中获取文件名?(How to get a files name from the complete path string?)用System.IO.Path.GetFileName 和 Syst

35、em.IO.Path.GetFileNameWithoutExtension(无扩展名)的方法12. 如何从完整的路径中获取文件扩展名?(How to get a files extension from the complete path string?)用System.IO.Path.GetExtension方法13. 如何使没有选择日期的DateTimePicker 控件为空文本?(How to make the DateTimePicker show empty text if no date is selected?)dateTimePicker1.CustomFormat = ;

36、dateTimePicker1.Format = DateTimePickerFormat.Custom; 14. 如何在 Report Viewer 中隐藏 Crystal Report 的状态栏?( How to hide the status bar of Crystal Report in Report Viewer?)foreach(object obj in this.crystalReportViewer1.Controls) if( obj.GetType()= typeof(System.Windows.Forms.StatusBar) StatusBar sBar=(Sta

37、tusBar)obj; sBar.Visible=false; 15. 如何利用 Crystal Report程序来生成 PDF 版本?( How to generate PDF version of Crystal Report programmatically?)ReportDocument O_Report=new ReportDocument(); ExportOptions exportOpts = new ExportOptions(); PdfRtfWordFormatOptions pdfFormatOpts = new PdfRtfWordFormatOptions ();

38、DiskFileDestinationOptions diskOpts = new DiskFileDestinationOptions(); exportOpts = O_Report.ExportOptions; / 设置PDF 格式exportOpts.ExportFormatType = ExportFormatType.PortableDocFormat; exportOpts.FormatOptions = pdfFormatOpts; / 设置文件选项和导出exportOpts.ExportDestinationType = ExportDestinationType.DiskF

39、ile; diskOpts.DiskFileName = C:/Trial.pdf; /设置 PDF 导出路径exportOpts.DestinationOptions = diskOpts; O_Report.Export (); 16. 通过代码如何输入多行文本?(How to enter multiline text in textbox through code? )利用 TextBox控件的 LINES属性string strAddress = Mukund Pujari,Global Transformation Technologies,Pune, India; textBox1

40、.MultiLine=true; textBox1.Lines=strAddress; 或者textBox1.Text=Line 1rnLine2rnLine3.; 或者用System.Environment.NewLine来替代换行符号17. 如何在 DataGrid 中去掉 CheckBox不确定状态?( How to remove the indeterminate status of checkbox in datagrid?)DataGridTableStyle ts1 = new DataGridTableStyle(); /创建 Table 样式ts1.MappingName =

41、 Items; /分配要应用样式的Data Table DataGridColumnStyle boolCol = new DataGridBoolColumn(); / 创建CheckBox列boolCol.MappingName = ch; /分配数据列名称boolCol.AllowNull=false; / 修改 AllowNull属性18. 如何在用一个数据源DataTable 绑定两个控件,确保变化不反映在两个控件中?( How to bind two controls to the same DataTable without having changes in one contr

42、ol also change the other control?)我们在一个 Form中放置一个 ListBox 和一个 ComboBox 控件,当数据源是一个DataTable 而且绑定的 ValueMember一致的时候我们选择ListBox 中的一个 Item 时,ComboBox 控件中的相同的Item 也会被自动选中,我们可以采取建立新的上下文绑定对象来拒绝这样的同步操作comboBox1.DataSource = dataset.Tables Items ; comboBox1.ValueMember = CustomerID; comboBox1.DisplayMember =

43、 CustomerID; listBox1.BindingContext = new BindingContext(); / 设置新的上下文绑定对象listBox1.DataSource = dataset.Tables Items ; listBox1.ValueMember = CustomerID; listBox1.DisplayMember = CustomerID; 19. 一个简单的创建链接字符串的方法。(An easy way to build connection string.)记事本创建一个 New.udl 的文件,一个 Microsoft 数据链接文件双击打开,熟悉吧按

44、照向导创建完成一个数据库链接,测试成功确定后,链接字符串写入这个文件,用记事本打开就看到了20. 如何打开客户端 EMail 程序,Windows应用和 Web 应用?( How to open default E-mail client on your system with all parameters entered in it,like Outlook Express or Eudora, from your .NET windows or Web Application? )Web Application:A href=mailto:,?cc=&Subject=Hello&body=

45、Happy New Year Windows Application:引用 System.Diagnostics.Process 命名空间Process process = new Process(); process.StartInfo.FileName = mailto:,?subject=Hello&cc= &bcc=&body=Happy New Year ; process.Start(); 21. VB.NET 和C# 有什么不同?( What is difference beween VB.NET and C#.NET? )去微软下载一个文档吧,http:/ 22. How to

46、 find whether your system has mouse or the number of buttons, whether it has wheel, or whether the mouse buttons are swapped or size of your monitor and many such information? 23. 如何使 Windows Form上的 Panel或者 Label 控件半透明?( How to make a Panel or Label semi-transparent on a Windows Form? )通过设置控件背景色的alp

47、ha 值panel1.BackColor = Color.FromArgb(65, 204, 212, 230); 注意:在设计时手动输入这些值,不要用颜色选取24. C#程序的主函数写 STA Thread 属性是什么目的?(What is the purpose of the STA Thread attribute for the Main method of a C# program? )http:/ 25. 如何触发 Button 的Click 事件?( How to trigger a button click event? )button1.PerformClick(); 26. 看到别人的 Console.Writeline();后并没有关闭而退出,怎么也找不到方法,后来发现,只要按CTRL+F5 就可以,而不是按F5 以上代码执行结果: 请按任意键继续 . . . 27. 以前也只是在 “ 解决方案资源管理器” 里右击文件打开目录,其实可以在打开的tab 上右击就会出现: “ 打开所在的文件夹”

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 建筑/环境 > 施工组织

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号