摘录C#代码片段

1.保存数据到指定文件
String response = "";//数据 byte[] bytes = response.getBytes();//转化Byte string filename =“asd”;//自己指定保存的文件名 FileStream fs = new FileStream(@"d:\" + filename + ".txt", FileMode.OpenOrCreate, FileAccess.Write);//自己指定路径 StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.GetEncoding("GB2312"));//通过指定字符编码方式可以实现对汉字的支持,否则在用记事本打开查看会出现乱码 sw.Flush(); sw.BaseStream.Seek(0, SeekOrigin.Begin); sw.WriteLine(bytes); sw.Flush(); sw.Close();

 2.Invoke.[form.show()]

Type type = Type.GetType("[namespace]." + form);

if (type != null)

{

      MethodInfo method = type.GetMethod("ShowDialog", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { }, null);

      object obj = type.Assembly.CreateInstance(type.FullName);

      method.Invoke(obj, null);

}

3.时间换算

//这样对 long 做除法会出误差(不能整除的时候)

public long getTimeInMillis()  

{  

return Decimal.ToInt64(Decimal.Divide(DateTime.Now.Ticks - 621355968000000000, 10000));

}  

//Linux 时间是从 Epoch 开始算的,1970-01-01 00:00:00.//000 叫“Epoch”。 

// 使用 DateTime.Now 的时候注意时区问题!//Java 是以 UTC 为基准的,而经查证,.NET 中与其对应的 是 DateTime.UtcNow 而非 DateTime.Now!  

 //所以,最后的结论就是:  

return Decimal.ToInt64(Decimal.Divide(DateTime.Now.Ticks - new DateTime(1970, 1, 1, 8, 0, 0).Ticks, 10000))  

 //或者  

return Decimal.ToInt64(Decimal.Divide(DateTime.UtcNow.Ticks - 621355968000000000, 10000));

4.随机颜色

public System.Drawing.Color GetRandomColor()

{

  Random RandomNum_First = new Random((int)DateTime.Now.Ticks);

  //  对于C#的随机数,没什么好说的

  System.Threading.Thread.Sleep(RandomNum_First.Next(50));

  Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);

//  为了在白色背景上显示,尽量生成深色

  int int_Red = RandomNum_First.Next(256);

  int int_Green = RandomNum_Sencond.Next(256);

  int int_Blue = (int_Red + int_Green > 400) ? 0 : 400 - int_Red - int_Green;

  int_Blue = (int_Blue > 255) ? 255 : int_Blue;

   return System.Drawing.Color.FromArgb(int_Red, int_Green, int_Blue);

}

5.搞不懂

**对于一些大型的项目,通常由很多个DLL文件组成,引用了这些DLL,就能访问DLL里面的类和类里面的方法。
比如,你写了一个记录日志的DLL,任何项目只要引用此DLL就能实现记录日志的功能,这个DLL文件的程序就是一个程序集。
如果你记录日志的程序集是这么定义的
namespace LogerHelper {
    internal class aa{
         public void bb(){
             return ""; } }
    public class Write{
        public void WriteIn(string content){
            class x = new aa();    
            x.bb();}}}
当另一个项目引用了此DLL
它可以这么访问  
LogerHelper.Write x = new LogerHelper.Write();
x.WriteIn("");
但不可以这么访问
LogerHelper.aa x = new LogerHelper.aa();
x.bb();
这就叫,只能在程序集中访问

6.枚举+随机

class Program{
static void Main(string[] args){
   Color[] colors = Enum.GetValues(typeof(Color)) as Color[];
   Random random = new Random();
   Color color = colors[random.Next(0, colors.Length)];}}
internal enum Color{
   White,Black,Red,Green,Pink}

 7.threadsleep

using System.Threading; //导入命名空间,类Thread就在此空间中

Thread.Sleep(10000);

 8.系统字体颜色字体大小

if (MessageBox.Show("     ?", "提示", MessageBoxButtons.YesNo) ==DialogResult.Yes) {}

FontFamily获取:

//前台有个familyList(DropDownList控件)

for(int i=0;i<FontFamily.Families.Length;i++)

{

  familyList.Items.Add(FontFamily.Families[i].Name);

}

//InstalledFontCollection

InstalledFontCollection ifc=new InstalledFontCollection();

foreach(FontFamily ff in ifc.Families)

{

 familyList2.Items.Add(ff.Name);

}

获取系统已安装的颜色:

//System.Drawing.KnownColor

string[] colors=Enum.GetNames(typeof(System.Drawing.KnownColor);

foreach(string color in colors)

{

 ListItem list=new ListItem(color);

 list.Attributes.Add("style","color:"+color);

 colorList.Items.Add(list);

}

获取字体大小:

//System.Web.UI.WebControls.FontSize

string[] sizes=Enum.GetName(typeof(System.Web.UI.WebControls.FontSize));

foreach(string size in sizes)

{

 sizeList.Items.Add(size);

}

9.快捷键

一、 C# button快捷键之第一种:Alt + *(按钮快捷键)

在大家给button、label、menuStrip等控件设置Text属性时在名字后边加&键名就可以了,比如button1.text= "确定(&O)"。就会有快捷键了,这时候按Alt+O就可以执行按钮单击事件。

二、C# button快捷键之第二种:Ctrl+*及其他组合键

在WinForm中设置要使用组合键的窗体的KeyPreview(向窗体注册键盘事件)属性为True;
然后使用窗体的KeyDown事件(在首次按下某个键时发生).

C# button快捷键实例代码如下:

private void ***_KeyDown(object sender, KeyEventArgs e)

{

if (e.KeyCode == Keys.F && e.Control)

 {

 button1.PerformClick(); //执行单击button1的动作

}

}

此处注意:

1、***代表窗体名称,看一下 ”Keys”的枚举参数,以实现自己的需要

2、还有一个问题,当使用Ctrl + *快捷键时,对于焦点在可写的控件(如TextBox)上时,可能会将* 键值同时输入,则需要加另一句话将Handled设置为true,以取消 KeyPress 事件。即:

private void ***_KeyDown(object sender, KeyEventArgs e)

{

  if (e.KeyCode == Keys.F && e.Control)

  {

    e.Handled = true;  //将Handled设置为true,指示已经处理过KeyPress事件

    button1.PerformClick();  

  }

}

三、C# button快捷键之第三种方法

还是以button为例。给form添加一个contextMenuStrip1,将其邦定到button上,假设为button1。给 contextMenuStrip1添加一个item,然后为它设置快捷键(就是你想加在button上的快捷键),并且将它的Visible属性设为 false。这样,C# button快捷键设置成功。

四、C# button快捷键之第四种方法

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)

{

 if (keyData == (Keys.Escape))

 {

   this.Close();

 }

 return base.ProcessCmdKey(ref msg, keyData);

}

10.DataTable Set PrimaryKey:

if (dt.PrimaryKey == null || dt.PrimaryKey.Length == 0)
{
     dt.PrimaryKey = new DataColumn[] { dt.Columns["PK_ColunmeName"] };
}

DataRow myDataRow= myDataSet.Tables["TableName"].Rows.Find("primary key data");

11.Find the ContextMenuStrip(Contrl) ‘s ParentControl

stringcontrol_name= (senderasContextMenuStrip).SourceControl.Name;

转载于:https://www.cnblogs.com/lenkaset/p/6385360.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值