九溪

溪水润知林,滴露启慧心

用户工具

站点工具


home

Home

屏幕截屏

screencapture.cs
/// <summary>
/// 提供全屏和指定窗口的截图 以及保存为文件的类
/// </summary>
public class ScreenCapture
{
    /// <summary>
    /// 全屏截图
    /// </summary>
    /// <returns></returns>
    public Image CaptureScreen()
    {
        return CaptureWindow( User32.GetDesktopWindow() );
    }
    /// <summary>
    /// 指定窗口截图
    /// </summary>
    /// <param name="handle">窗口句柄. (在windows应用程序中, 从Handle属性获得)</param>
    /// <returns></returns>
    public Image CaptureWindow(IntPtr handle)
    {
        IntPtr hdcSrc = User32.GetWindowDC(handle);
        User32.RECT windowRect = new User32.RECT();
        User32.GetWindowRect(handle,ref windowRect);
        int width = windowRect.right - windowRect.left;
        int height = windowRect.bottom - windowRect.top;
        IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
        IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc,width,height);
        IntPtr hOld = GDI32.SelectObject(hdcDest,hBitmap);
        GDI32.BitBlt(hdcDest,0,0,width,height,hdcSrc,0,0,GDI32.SRCCOPY);
        GDI32.SelectObject(hdcDest,hOld);
        GDI32.DeleteDC(hdcDest);
        User32.ReleaseDC(handle,hdcSrc);
        Image img = Image.FromHbitmap(hBitmap);
        GDI32.DeleteObject(hBitmap);
        return img;
    }
    /// <summary>
    /// 指定窗口截图 保存为图片文件
    /// </summary>
    /// <param name="handle"></param>
    /// <param name="filename"></param>
    /// <param name="format"></param>
    public void CaptureWindowToFile(IntPtr handle, string filename, ImageFormat format)
    {
        Image img = CaptureWindow(handle);
        img.Save(filename,format);
    }
    /// <summary>
    /// 全屏截图 保存为文件
    /// </summary>
    /// <param name="filename"></param>
    /// <param name="format"></param>
    public void CaptureScreenToFile(string filename, ImageFormat format)
    {
        Image img = CaptureScreen();
        img.Save(filename,format);
    }
 
    /// <summary>
    /// 辅助类 定义 Gdi32 API 函数
    /// </summary>
    private class GDI32
    {
 
        public const int SRCCOPY = 0x00CC0020;
        [DllImport("gdi32.dll")]
        public static extern bool BitBlt(IntPtr hObject,int nXDest,int nYDest,
            int nWidth,int nHeight,IntPtr hObjectSource,
            int nXSrc,int nYSrc,int dwRop);
        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC,int nWidth,
            int nHeight);
        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
        [DllImport("gdi32.dll")]
        public static extern bool DeleteDC(IntPtr hDC);
        [DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr hObject);
        [DllImport("gdi32.dll")]
        public static extern IntPtr SelectObject(IntPtr hDC,IntPtr hObject);
    }
 
    /// <summary>
    /// 辅助类 定义User32 API函数
    /// </summary>
    private class User32
    {
        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int left;
            public int top;
            public int right;
            public int bottom;
        }
        [DllImport("user32.dll")]
        public static extern IntPtr GetDesktopWindow();
        [DllImport("user32.dll")]
        public static extern IntPtr GetWindowDC(IntPtr hWnd);
        [DllImport("user32.dll")]
        public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDC);
        [DllImport("user32.dll")]
        public static extern IntPtr GetWindowRect(IntPtr hWnd,ref RECT rect);
    }
}
2018/02/03 20:43

能够自适应窗体大小的WinForm 控件

//窗体初始化
public frmAutoSketch()
{
InitializeComponent();
//在窗体中放一个容器(例如:Panel),并且将容器的Dock属性设置为Fill。窗体中其他控件都放在这个容器中。
    this.panel_AutoSketch.Dock = DockStyle.Fill;
    GetAllInitInfo(this.panel_AutoSketch);
    this.SizeChanged += frmSketchFormcs_SizeChanged;
}
//窗体大小更改时更新空间大小
void frmSketchFormcs_SizeChanged(object sender, EventArgs e)
{
    if (controlInfo.Count > 0)
    {
        ControlsChangeInit(this.Controls[0]);
        ControlsChange(this.Controls[0]);
    }
}
#region 控件缩放
double formWidth;//窗体原始宽度
double formHeight;//窗体原始高度
double scaleX;//水平缩放比例
double scaleY;//垂直缩放比例
Dictionary<string, string> controlInfo = new Dictionary<string, string>();//控件中心Left,Top,控件Width,控件Height,控件字体Size
/// <summary>
/// 获取所有原始数据
/// </summary>
private void GetAllInitInfo(Control CrlContainer)
{
    if (CrlContainer.Parent == this)
    {
        formWidth = Convert.ToDouble(CrlContainer.Width);
        formHeight = Convert.ToDouble(CrlContainer.Height);
    }
    foreach (Control item in CrlContainer.Controls)
    {
        if (item.Name.Trim() != "")
            controlInfo.Add(item.Name, (item.Left + item.Width / 2) + "," + (item.Top + item.Height / 2) + "," + item.Width + "," + item.Height + "," + item.Font.Size);
        if ((item as UserControl) == null && item.Controls.Count > 0)
            GetAllInitInfo(item);
    }
}
private void ControlsChangeInit(Control CrlContainer)
{
    scaleX = (Convert.ToDouble(CrlContainer.Width) / formWidth);
    scaleY = (Convert.ToDouble(CrlContainer.Height) / formHeight);
}
private void ControlsChange(Control CrlContainer)
{
    double[] pos = new double[5];//pos数组保存当前控件中心Left,Top,控件Width,控件Height,控件字体Size
    foreach (Control item in CrlContainer.Controls)
    {
        if (item.Name.Trim() != "")
        {
            if ((item as UserControl) == null && item.Controls.Count > 0)
                ControlsChange(item);
            string[] strs = controlInfo[item.Name].Split(',');
            for (int j = 0; j < 5; j++)
            {
                pos[j] = Convert.ToDouble(strs[j]);
            }
            double itemWidth = pos[2] * scaleX;
            double itemHeight = pos[3] * scaleY;
            item.Left = Convert.ToInt32(pos[0] * scaleX - itemWidth / 2);
            item.Top = Convert.ToInt32(pos[1] * scaleY - itemHeight / 2);
            item.Width = Convert.ToInt32(itemWidth);
            item.Height = Convert.ToInt32(itemHeight);
            item.Font = new Font(item.Font.Name, float.Parse((pos[4] * Math.Min(scaleX, scaleY)).ToString()));
        }
    }
}
#endregion
2018/02/03 20:43

ListView控件的常用操作

listView1.Columns.Clear();//清空列记录
ColumnHeader cZh = new ColumnHeader();//创建一个列
cZh.Text = "英文";//列名
ColumnHeader cCh = new ColumnHeader();
cCh.Text = "中文";
listView1.Columns.AddRange(new ColumnHeader[] { cZh, cCh });//将这两列加入listView1
listView1.View = View.Details;//列的显示模式
ListViewItem lvi = new ListViewItem(new string[] { "dog","狗"}, -1);//创建列表项
listView1.Items.Add(lvi);//将项加入listView1列表中
2018/02/03 20:43

控件闪烁处理办法

就是在这个窗体的构造函数中增加以下三行代码: 请在构造函数里面底下加上如下几行:

SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲

参数说明:

UserPaint 
如果为 true,控件将自行绘制,而不是通过操作系统来绘制。此样式仅适用于派生自 Control 的类。

AllPaintingInWmPaint 
如果为 true,控件将忽略 WM_ERASEBKGND 窗口消息以减少闪烁。仅当 UserPaint 位设置为 true 时,才应当应用该样式。 

DoubleBuffer 
如果为true,则绘制在缓冲区中进行,完成后将结果输出到屏幕上。双重缓冲区可防止由控件重绘引起的闪烁。要完全启用双重缓冲,还必须将 UserPaint 和 AllPaintingInWmPaint 样式位设置为 true。
2018/02/03 20:43

对数据结构排序

#region 对数据结构排序
/// <summary>
/// 对数据结构排序
/// </summary>
/// <param name="list">数据列表</param>
/// <param name="order">升序排列</param> 
/// <param name="strProperty">排序字段</param>
/// <param name="_isFigure">字段为数字类型</param>
/// <returns></returns>
private List<IPlaneShow> SortIPlaneShows(IPlaneShow[] list, bool order, string strProperty, bool _isFigure)
{
    curSortProperty = strProperty;
    IsOrderly = order;
    IsFigure = _isFigure;
    Comparison<IPlaneShow> com = new Comparison<IPlaneShow>(Compare);
    List<IPlaneShow> listOri = new List<IPlaneShow>();
    listOri.AddRange(list);
    listOri.Sort(com); 
    return listOri; 
}
#region 排序辅助
//排序字段
string curSortProperty = "";
//顺序排序
bool IsOrderly = true;
//是否为数字类型的字段
bool IsFigure = false;
//排序器
int Compare(IPlaneShow A, IPlaneShow B)
{
    int result;
    CaseInsensitiveComparer objCompare = new CaseInsensitiveComparer();
    string strA = A.GetType().GetProperty(curSortProperty).GetValue(A, null).ToString();
    string strB = B.GetType().GetProperty(curSortProperty).GetValue(B, null).ToString();
    if (IsFigure)
    {
        //数字排序
        double dA = double.Parse(strA);
        double dB = double.Parse(strB);
        result = objCompare.Compare(strA, strB);
    }
    else
    {
        //字符排序
        result = objCompare.Compare(strA, strB);
    } 
    //正反序
    if (IsOrderly)
        result *= -1;
    return result;
} 
#endregion
#endregion
2018/02/03 20:43

评论

1xbet, 2025/04/30 12:14

I'd suggest this article to everyone curious about this field. Clear descriptions of important ideas. 1xbet

1xbet, 2025/04/30 12:14

I'd suggest this article to everyone curious about this field. Clear descriptions of important ideas. 1xbet

1xbet, 2025/04/30 11:35

I completely concur with your main argument. Additionally, I would add that this aspect is equally important. 1xbet

1xbet, 2025/04/30 11:35

I completely concur with your main argument. Additionally, I would add that this aspect is equally important. 1xbet

mostbet РФ, 2025/04/29 13:44

mostbet РФ Your fortune awaits! Enjoy exclusive bonuses! Stay tuned for special events! Subscribe to our newsletter for more! Play big! Tell your colleagues about us! Huge thanks for being part of us! Very professional! Our site is fantastic! Following your latest events! Liked and registered! You're an undisputed expert! Will share with on social media! Thank you for your assistance! Very rewarding experience! Your efforts always lead to wins! mostbet играть mostbet Кыргызстан mostbet mostbet kz

mostbet РФ, 2025/04/29 13:44

mostbet РФ Your fortune awaits! Enjoy exclusive bonuses! Stay tuned for special events! Subscribe to our newsletter for more! Play big! Tell your colleagues about us! Huge thanks for being part of us! Very professional! Our site is fantastic! Following your latest events! Liked and registered! You're an undisputed expert! Will share with on social media! Thank you for your assistance! Very rewarding experience! Your efforts always lead to wins! mostbet играть mostbet Кыргызстан mostbet mostbet kz

mostbet Azərbaycan, 2025/04/27 22:59

mostbet Azərbaycan Hit the jackpot with us! Unlock your fortune! Play with ease on our licensed platform! Don't miss out on huge jackpots! Win big! Share the joy with friends! Grateful for your loyalty! Simply fantastic! Your efforts always result in victories! Eagerly awaiting your upcoming tournaments! Bookmarked your content in my browser! You're the best! Telling everyone! Thanks for the rewarding experience! Very exciting promotion! Your skills always are rewarded! mostbet ru mostbet mostbet today mostbet Киргизия

mostbet Azərbaycan, 2025/04/27 22:59

mostbet Azərbaycan Hit the jackpot with us! Unlock your fortune! Play with ease on our licensed platform! Don't miss out on huge jackpots! Win big! Share the joy with friends! Grateful for your loyalty! Simply fantastic! Your efforts always result in victories! Eagerly awaiting your upcoming tournaments! Bookmarked your content in my browser! You're the best! Telling everyone! Thanks for the rewarding experience! Very exciting promotion! Your skills always are rewarded! mostbet ru mostbet mostbet today mostbet Киргизия

1win, 2025/04/09 18:09

¡La fortuna te acompaña! No pierdas la oportunidad de disfrutar de apuestas seguros y entretenidas en 1Win. 1win

1win, 2025/04/09 18:09

¡La fortuna te acompaña! No pierdas la oportunidad de disfrutar de apuestas seguros y entretenidas en 1Win. 1win

bet9ja old mobile, 2025/04/09 18:07

Discover Bet9ja: The Best Betting Experience in Nigeria!

bet9ja old mobile Looking for a simple betting experience? Access the Bet9ja Old Mobile version and experience fast loading times and easy navigation. Bet on soccer, casino games, and virtual races without the complexities of the new version. Start betting in minutes!

old bet9ja

bet9ja old mobile, 2025/04/09 18:07

Discover Bet9ja: The Best Betting Experience in Nigeria!

bet9ja old mobile Looking for a simple betting experience? Access the Bet9ja Old Mobile version and experience fast loading times and easy navigation. Bet on soccer, casino games, and virtual races without the complexities of the new version. Start betting in minutes!

old bet9ja

pinco, 2025/04/09 18:05

Pinco Casino'da eğlence sizi bekliyor! pinco

Pinco Casino'da hızla kayıt olabilirsiniz. Bonuslu oyunlar ve yüksek ödeme oranları ile oyun deneyiminizi zenginleştirin. pinco

pinco, 2025/04/09 18:05

Pinco Casino'da eğlence sizi bekliyor! pinco

Pinco Casino'da hızla kayıt olabilirsiniz. Bonuslu oyunlar ve yüksek ödeme oranları ile oyun deneyiminizi zenginleştirin. pinco

pin up casino india, 2025/04/09 18:04

Exciting casino options await you at Pin-Up! At Pin-Up Casino, you'll find engaging slot games, table games, sports wagers, and much more. Play premium games from top providers like NetEnt and Microgaming, and take your chance for huge wins!

pin up casino india Maximizing the ?450000 Welcome Bonus at Pin-Up Casino. The Pin Up casino welcome offer of up to ?450000 is generous, but how can you take full advantage of it? Have you received this offer yet? Let us know your strategies and tips for transforming the bonus into huge payouts. Let’s talk about how to make the most out of your first top-up!

pin up casino india, 2025/04/09 18:04

Exciting casino options await you at Pin-Up! At Pin-Up Casino, you'll find engaging slot games, table games, sports wagers, and much more. Play premium games from top providers like NetEnt and Microgaming, and take your chance for huge wins!

pin up casino india Maximizing the ?450000 Welcome Bonus at Pin-Up Casino. The Pin Up casino welcome offer of up to ?450000 is generous, but how can you take full advantage of it? Have you received this offer yet? Let us know your strategies and tips for transforming the bonus into huge payouts. Let’s talk about how to make the most out of your first top-up!

taya365 app, 2025/04/09 18:04

Use Taya365 bonuses for maximum victories taya365 app Uncover the world of online gaming with Taya365 and enjoy top-notch live games. Register today to receive huge rewards and bonuses! Taya365 and enjoy a world of adventure. Whether you're into sports betting, there's something to enjoy. Get started and win big! taya365 app download

taya365 app, 2025/04/09 18:04

Use Taya365 bonuses for maximum victories taya365 app Uncover the world of online gaming with Taya365 and enjoy top-notch live games.

Register today to receive huge rewards and bonuses! Taya365 and enjoy a world of adventure. Whether you're into sports betting, there's something to enjoy. Get started and win big! taya365 app download

Online betting in Egypt, 2025/04/04 06:20

دائماً أراهن في 1xbet Sports Betting Egypt – مضمون ومربح! أوصي به الآن! Online betting in Egypt

Online betting in Egypt, 2025/04/04 06:20

دائماً أراهن في 1xbet Sports Betting Egypt – مضمون ومربح!

أوصي به الآن! Online betting in Egypt

Mostbet BD, 2025/04/03 05:44

Mostbet জুয়া – বিশাল প্ল্যাটফর্ম ভার্চুয়াল গেমস জন্য। Mostbet BD

Mostbet BD, 2025/04/03 05:44

Mostbet জুয়া – বিশাল প্ল্যাটফর্ম ভার্চুয়াল গেমস জন্য। Mostbet BD

mostbet kazakhstan, 2025/04/01 04:33

Онлайн казино Mostbet – кең ауқымды мүмкіндіктер ұсынады спорттық ставкалар сүйінушілеріне.

mostbet kazakhstan

mostbet kazakhstan, 2025/04/01 04:33

Онлайн казино Mostbet – кең ауқымды мүмкіндіктер ұсынады спорттық ставкалар сүйінушілеріне. mostbet kazakhstan

mega moriarty, 2025/03/30 23:23

На данном сайте всегда доступна актуальная ссылка на мега мориарти, которая обновляется регулярно, чтобы вы могли без проблем попасть на нужную платформу.

mega moriarty, 2025/03/30 23:23

На данном сайте всегда доступна актуальная ссылка на мега мориарти, которая обновляется регулярно, чтобы вы могли без проблем попасть на нужную платформу.

why 1xbet is the best online casino site for UAE players Thank you for your openness and openness! �� 400 Bad Request

why 1xbet is the best online casino site for UAE players Thank you for your openness and openness! �� 400 Bad Request

1xBet تسجيل, 2025/03/19 08:29

دائماً أراهن في 1xbet مصر – مضمون ومثالي! جربه بنفسك الآن! 1xBet تسجيل

1xBet تسجيل, 2025/03/19 08:29

دائماً أراهن في 1xbet مصر – مضمون ومثالي! جربه بنفسك الآن! 1xBet تسجيل

1xBet عروض ترويجية, 2025/03/17 21:23

جربت 1xbet Mobile App Egypt – يتميز بواجهة ممتازة، السحب دون مشاكل!

1xBet عروض ترويجية

1xBet عروض ترويجية, 2025/03/17 21:23

جربت 1xbet Mobile App Egypt – يتميز بواجهة ممتازة، السحب دون مشاكل!

1xBet عروض ترويجية

Jogar FortuneRabbit sempre foi tão simples., 2025/03/14 23:47

هل تحتاج إلى أشهر شركة رهان؟ 1xbet شركة الرهان يقدم أقوى الفرص ودفعات سريعة! Jogar FortuneRabbit sempre foi tão simples.

Nam, 2025/03/14 23:47

هل تحتاج إلى أشهر شركة رهان؟ 1xbet شركة الرهان يقدم أقوى الفرص ودفعات سريعة!

Jogar FortuneRabbit sempre foi tão simples.

1xBet in Egypt, 2025/03/04 22:58

دائماً أشارك في 1xbet Sports Betting Egypt – مريح ومربح! أنصح به الآن! 1xBet in Egypt

Dalene, 2025/03/04 22:57

دائماً أشارك في 1xbet Sports Betting Egypt – مريح ومربح! أنصح به الآن! 1xBet in Egypt

1xBet تطبيق الجوال, 2025/03/04 09:47

هل تبحث عن أقوى كازينو أونلاين؟ 1xbet Egypt يقدم أفضل العروض ودفعات سريعة! 1xBet تطبيق الجوال

Sherlyn, 2025/03/04 09:47

هل تبحث عن أقوى كازينو أونلاين؟ 1xbet Egypt يقدم أفضل العروض ودفعات سريعة! 1xBet تطبيق الجوال

Apostas em futebol, 2025/02/18 15:48

دائماً أراهن في 1xbet مصر – مريح ومثالي!

أنصح به الآن! Apostas em futebol

Jamel, 2025/02/18 15:48

دائماً أراهن في 1xbet مصر – مريح ومثالي! أنصح به الآن! Apostas em futebol

请输入您的评论. 可以使用维基语法:
 
home.txt · 最后更改: 2025/02/27 17:17 由 colin