C# 开发常见问题

        //-----------------------------------------------------------------
扩展控件
添加 用户控件 
继承基本控件,扩展一些属性与事件。比如继承Button



步骤一:这里首先要建一个Windows控件库项目。
步骤二:新建用户控件,修改代码(注意注释掉.Designer.cs文件中的代码)
扩展Button
复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WinFormControlLibrary
{
public partial class UcButton : Button
{
public UcButton()
{
InitializeComponent();
}
// Creates the private variable that will store the value of your 
// property.
private int varValue;
// Declares the property.
public int ButtonValue
{
// Sets the method for retrieving the value of your property.
get
{
return varValue;
}
// Sets the method for setting the value of your property.
set
{
varValue = value;
}
}
}
}
复制代码
修改.Desinger.cs
复制代码
namespace WinFormControlLibrary
{
partial class UcButton
{
/// <summary> 
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary> 
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary> 
/// Required method for Designer support - do not modify 
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
//把这句注释掉
//this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
}
#endregion
}
}

//-----------------------------------------------------------------
g.SmoothingMode = SmoothingMode.None;
g.InterpolationMode = InterpolationMode.NearestNeighbor;
g.PixelOffsetMode = PixelOffsetMode.Half;

   g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//-----------------------------------------------------------------
c#中的定点旋转
网上有网友在问关于图形定点旋转的问题,因为默认的旋转是以图形中心来进行的,而有时候,的确需要在某个点为中心进行旋转。相当于做一个平移再做一个旋转。C#中的Matrix类可以很轻易的实现这个功能。代码如下:
Matrix myMatrix = new Matrix();
Single angle = 0;
PointF rotatePoint = new PointF(X, Y);//定点中心坐标(x,y)
myMatrix.RotateAt(angle, rotatePoint, MatrixOrder.Append);
Graphics g = Graphics.FromImage(图片对象名);
g.Transform = myMatrix;
g.DrawImage(需旋转的图片对象名, new Point(0, 0));



另一种旋转的方法:
private void Form1_Paint(object sender, PaintEventArgs e)
        {


            Graphics graphics = e.Graphics;
            var picRect = new RectangleF(200, 200, 100, 50);
            PointF[] points = new PointF[] {  // 将原来四边形的4个顶点坐标放入数组
                                     picRect.Location,
                                     new PointF(picRect.Right, picRect.Top),
                                     new PointF(picRect.Right, picRect.Bottom),
                                     new PointF(picRect.Left, picRect.Bottom)
                                    };
            graphics.DrawPolygon(new Pen(Color.Red), points);
            Matrix matrix=new Matrix();


            //更改坐标系
            graphics.TranslateTransform(100, 100);
            //旋转角度
            graphics.RotateTransform(10);
            //恢复坐标系
//恢复图像在水平和垂直方向的平移
            graphics.TranslateTransform(-100, -100);


            //获取旋转后的坐标
            graphics.Transform.TransformPoints(points);


            graphics.DrawPolygon(new Pen(Color.Red), points);
        }
//-----------------------------------------------------------------
  在一个项目中需要给picturebox增加滚动条


方法是:1.将picturebox放在panel上;


      2.将panel的AutoScroll设置为ture;


      3.将picturebox的SizeMode设置为AutoSize;


      4.将picturebox的Dock设置为None.


    //-----------------------------------------------------------------
C# 解决DrawImage绘制图片拉伸产生渐变


ImageAttributes ImgAtt = new ImageAttributes(); ;
ImgAtt.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY);
 
m_graphics.DrawImage(image, new System.Drawing.Rectangle((int)(x - width / 2 + backBmp1.Width), (int)(y - pixel + 1), backBmp2.Width, backBmp2.Height), 0, 0, backImage2.Width, backImage2.Height, GraphicsUnit.Pixel,ImgAtt);

//-----------------------------------------------------------------

C#中如何打开一个指定的文件夹
Click事件里写


string path = @"D:\Program Files";
System.Diagnostics.Process.Start("explorer.exe", path);


就可以了, 调用explorer资源管理器打开吧?
windows窗口当然要调系统的东西了~`


//-----------------------------------------------------------------


 c# 如何读取文件夹中的所有文件
 string[] files = Directory.GetFiles(@"e:\jfy\");
 foreach (string file in files)
 Response.Write(file);

 foreach (string file in files)
 Response.Write(Path.GetFileName(file));


//-----------------------------------------------------------------
c# 判断文件是否发生了变化

你这个是想文件发生改变时,自动调用一个函数,做出一些操作呢。
还是有一个按钮(或者别的什么),你去点击一下,然后检测下一个文件,是否发生了变化?
下面的代码,监控d盘下的所有.txt文件的修改


        static void TestFileSystemWatcher()
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            try
            {
                watcher.Path = @"d:\Test";
            }
            catch (ArgumentException e)
            {
                Console.WriteLine(e.Message);
                return;
            }
 
            //设置监视文件的哪些修改行为
            watcher.NotifyFilter = NotifyFilters.LastAccess
                | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
 
 
            watcher.Filter = "*.txt";
 
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnChanged);
            watcher.Deleted += new FileSystemEventHandler(OnChanged);
            watcher.Renamed += new RenamedEventHandler(OnRenamed);
 
            watcher.EnableRaisingEvents = true;
 
            Console.WriteLine(@"Press 'q' to quit app.");
 
            while (Console.Read() != 'q');
        }
 
        static void OnChanged(object source, FileSystemEventArgs e)
        {
            Console.WriteLine("File:{0} {1}!", e.FullPath, e.ChangeType);
        }
 
        static void OnRenamed(object source, RenamedEventArgs e)
        {
            Console.WriteLine("File:{0} renamed to\n{1}", e.OldFullPath, e.FullPath);
        }


//-----------------------------------------------------------------

如何用C#编写程序监测某个文件夹内是否有文件进行了增,删,改的动作?

新建一个Console应用程序,项目名称为“FileSystemWatcher”,Copy代码进,编译后就可以用了。代码如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Permissions;
namespace MyFileSystemWatcher
{
public class Watcher
{
public static void Main(string[] args)
{
Run();
}
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public static void Run()
{
string[] args = System.Environment.GetCommandLineArgs();
if (args.Length != 2)
{
Console.WriteLine("使用方式: FileSystemWatcher.exe DirectoryPath");
return;
}
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = args[1];
/* 设置为监视 LastWrite 和 LastAccess 时间方面的更改,以及目录中文本文件的创建、删除或重命名。 */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
  | NotifyFilters.FileName | NotifyFilters.DirectoryName;
// 只监控.txt文件
watcher.Filter = "*.txt";
// 添加事件处理器。
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// 开始监控。
watcher.EnableRaisingEvents = true;
// 输入q推出程序。
Console.WriteLine("按 \'q\' 推出程序。");
while (Console.Read() != 'q') ;
}
// 定义事件处理器。
private static void OnChanged(object source, FileSystemEventArgs e)
{
//如果更改、创建或删除文件,文件路径将被输出到控制台。
Console.WriteLine("文件: " + e.FullPath + " " + e.ChangeType);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// 在文件重命名后,旧路径和新路径都输出到控制台。
Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}
}
}
使用说明(具体看图):
1、打开cmd窗口,先定位到FileSystemWatcher.exe所在的文件夹目录;
2、输入【FileSystemWatcher.exe 文件夹目录名称】,回车;
3、在监控的文件夹目录中增删改文件,就可以看见监控结果。

//-----------------------------------------------------------------

C# 调用DLL方法:

每种编程语言调用DLL的方法都不尽相同,在此只对用C#调用DLL的方法进行介绍。首先,您需要了解什么是托管,什么是非托管。一般可以认为:非托管代码主要是基于win 32平台开发的DLL,activeX的组件,托管代码是基于.net平台开发的。如果您想深入了解托管与非托管的关系与区别,及它们的运行机制,请您自行查找资料,本文件在此不作讨论。


(一)     调用DLL中的非托管函数一般方法
首先,应该在C#语言源程序中声明外部方法,其基本形式是:
[DLLImport(“DLL文件”)]
修饰符 extern 返回变量类型 方法名称 (参数列表)

其中:
DLL文件:包含定义外部方法的库文件。
修饰符: 访问修饰符,除了abstract以外在声明方法时可以使用的修饰符。
返回变量类型:在DLL文件中你需调用方法的返回变量类型。
方法名称:在DLL文件中你需调用方法的名称。
参数列表:在DLL文件中你需调用方法的列表。

注意:需要在程序声明中使用System.Runtime.InteropServices命名空间。
      DllImport只能放置在方法声明上。
DLL文件必须位于程序当前目录或系统定义的查询路径中(即:系统环境变量中Path所设置的路径)。
返回变量类型、方法名称、参数列表一定要与DLL文件中的定义相一致。

若要使用其它函数名,可以使用EntryPoint属性设置,如:
[DllImport("user32.dll", EntryPoint="MessageBoxA")]
static extern int MsgBox(int hWnd, string msg, string caption, int type);

其它可选的 DllImportAttribute 属性:

CharSet 指示用在入口点中的字符集,如:CharSet=CharSet.Ansi;
更重要的是它简化了对ANSI和Unicode版本的调用。CharSet用于标识函数调用所采用的是Unicode或是ANSI版本,ExactSpelling=false将告诉编译器,让编译器决定使用Unicode或者是Ansi版本
SetLastError 指示方法是否保留 Win32"上一错误",如:SetLastError=true;
ExactSpelling 指示 EntryPoint 是否必须与指示的入口点的拼写完全匹配,如:ExactSpelling=false;
PreserveSig指示方法的签名应当被保留还是被转换, 如:PreserveSig=true;
CallingConvention指示入口点的调用约定, 如:CallingConvention=CallingConvention.Winapi;

//--------------------------

public Rectangle(    int x,    int y,    int width,    int height)参数x类型: System .Int32 
矩形左上角的 x 坐标。
y类型: System .Int32 
矩形左上角的 y 坐标。
width类型: System .Int32 
矩形的宽度。
height类型: System .Int32 
矩形的高度。

//--------------------------

 坐标变换

默认情况下,坐标系的原点位于视图区域的左上角,水平方向为x轴,竖直方向为y轴。但有时候我们需要改变坐标轴的位置或方向,这时就需要坐标变换。常用的坐标变换有平移变换、旋转变换和伸缩变换三种。

平移变换
平移变换是指把坐标系的原点由一个位置平移到另一个位置,我们可以通过Graphics 类的TranslateTransform()方法实现平移变换。


//在新坐标系中绘制图形
    g.TranslateTransform(150, 120);

该语句把坐标系向右平移了150像素,向下平移了120像素,使坐标系的原点由A点平移到了B点(如虚线所示)。


6、辅助功能

 GraphicsState transState = e.Graphics.Save();//保存当前绘图板状态
e.Graphics.ResetTransform();//重置
e.Graphics.Restore(transState);//置为此状态


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值