FormImage.cs

来源:互联网 发布:网络金融理财产品排行 编辑:程序博客网 时间:2024/05/14 21:52

using System;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace BrowserImage
{
    public partial class FormImage : Form
    {
        #region
        private DataTable table;
        private ChineseLunisolarCalendar lunarCalendar;

        [DllImport("user32.dll", EntryPoint = "AnimateWindow")]
        private static extern bool AnimateWindow(IntPtr handle, int ms, int flags);
        #endregion

        public FormImage()
        {
            #region
            InitializeComponent();
            lunarCalendar = new ChineseLunisolarCalendar(); // 中国阴历。
            table = new DataTable();
            table.Locale = CultureInfo.InvariantCulture; // 固定区域性。
            DataColumn column = table.Columns.Add("Name", typeof(String));
            table.Columns.Add("Bytes", typeof(Byte[]));
            table.Constraints.Add("PK", column, true); // 创建主键。
            DataGridViewStyle();
            picture.SizeMode = PictureBoxSizeMode.Zoom; // 图像大小按其原有的大小比例被增加或减小。
            picture.MouseClick += new MouseEventHandler(picture_MouseClick);
            splitContainer1.FixedPanel = FixedPanel.Panel1; // 面板大小保持不变。
            splitContainer1.IsSplitterFixed = true; // 固定拆分器。
            splitContainer1.Orientation = Orientation.Vertical; //  垂直放置控件或元素。
            splitContainer1.SplitterDistance = 148; // 设置 FixedPanel.Panel1 宽度。
            toolComboBoxExt.DropDownStyle = ComboBoxStyle.DropDownList;
            toolComboBoxExt.ComboBox.DataSource = new string[] { "", "*.bmp", "*.gif", "*.jpg", "*.png" };
            this.BackColor = SystemColors.Window;
            this.StartPosition = FormStartPosition.CenterScreen;
            #endregion
        }

        #region OnLoad
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            AnimateWindow(this.Handle, 1000, 0x20010); // 居中逐渐显示。
        }
        #endregion

        #region OnFormClosing
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            AnimateWindow(this.Handle, 1000, 0x10010); // 居中逐渐隐藏。
        }
        #endregion

        #region OnDragEnter
        protected override void OnDragEnter(DragEventArgs e)
        {
            base.OnDragEnter(e);
            this.Activate(); // 激活窗体并给予它焦点。
            DataObject data = e.Data as DataObject;
            if (data.ContainsFileDropList())
            {
                table.BeginLoadData();
                foreach (string filePath in data.GetFileDropList())
                {
                    if (Regex.IsMatch(Path.GetExtension(filePath), @".(bmp|gif|jpg|png)", RegexOptions.IgnoreCase)) // 指定不区分大小写的匹配。
                    {
                        if (table.Rows.Contains(filePath))
                        {
                            MessageBox.Show(this, string.Format("图像“{0}”已存在!", filePath), "确认图片添加", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            continue;
                        }
                        table.Rows.Add(filePath, File.ReadAllBytes(filePath));
                    }
                }
                table.EndLoadData();
            }
        }
        #endregion

        #region DataGridViewStyle
        private void DataGridViewStyle()
        {
            DataGridViewImageColumn imgColumn = new DataGridViewImageColumn();
            imgColumn.DataPropertyName = "Bytes";
            imgColumn.ImageLayout = DataGridViewImageCellLayout.Zoom; // 将图形按比例放大,直到达到其所在单元格的宽度或高度。
            imgColumn.Width = 128; // 设置图片宽度。
            gridView.Columns.Add(imgColumn);
            gridView.RowTemplate.Height = 128; // 设置图片高度。
            gridView.BorderStyle = BorderStyle.Fixed3D;
            gridView.BackgroundColor = SystemColors.Window;
            gridView.AutoGenerateColumns = false; // 禁用自动创建列。
            gridView.AllowUserToAddRows = false; // 隐藏添加行。
            gridView.AllowUserToDeleteRows = false; // 禁用删除行。
            gridView.AllowUserToResizeRows = false; // 禁用调整行的大小。
            gridView.AllowUserToResizeColumns = false; // 禁用调整列的大小。
            gridView.ColumnHeadersVisible = false; // 隐藏列标题。
            gridView.RowHeadersVisible = false; // 隐藏行标题。
            gridView.ReadOnly = true; // 禁用编辑单元格。
            gridView.MultiSelect = false; // 用户仅能选择一个单元格、行或列。
            gridView.ShowCellToolTips = true; // 显示单元格工具提示。
            gridView.CellToolTipTextNeeded += new DataGridViewCellToolTipTextNeededEventHandler(gridView_CellToolTipTextNeeded);
            gridView.DataError += new DataGridViewDataErrorEventHandler(gridView_DataError);
            gridView.SelectionChanged += new EventHandler(gridView_SelectionChanged);
            gridView.DataSource = table.DefaultView;
        }

        private void gridView_SelectionChanged(object sender, EventArgs e)
        {
            DataGridViewCell cell = gridView.CurrentCell;
            if (cell != null)
            {
                this.Text = Path.GetFileName(cell.ToolTipText);
                picture.Image = cell.FormattedValue as Image;
                statusLabelImage.Text = string.Format("ImageSize = {0}", picture.Image.Size);
            }
            toolButtonDelete.Enabled = (cell != null);
            toolButtonSave.Enabled = toolButtonCopy.Enabled = (picture.Image != null);
        }

        private void gridView_CellToolTipTextNeeded(object sender, DataGridViewCellToolTipTextNeededEventArgs e)
        {
            e.ToolTipText = table.DefaultView[e.RowIndex][0] as string; // 设置工具提示文本。
        }

        private void gridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            table.DefaultView.Delete(e.RowIndex);
            (BindingContext[table.DefaultView] as CurrencyManager).Position = e.RowIndex;
            e.ThrowException = false; // 不引发异常。
        }
        #endregion

        #region CurrencyManager
        private void picture_MouseClick(object sender, MouseEventArgs e)
        {
            CurrencyManager manager = BindingContext[table.DefaultView] as CurrencyManager;
            switch (e.Button)
            {
                case MouseButtons.Left:
                    --manager.Position; // 显示上一个图片。
                    break;
                case MouseButtons.Right:
                    ++manager.Position; // 显示下一个图片。
                    break;
            }
        }
        #endregion

        #region CopyImage
        private void toolButtonCopy_Click(object sender, EventArgs e)
        {
            Clipboard.SetImage(picture.Image);
        }
        #endregion

        #region DeleteImage
        private void toolButtonDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(this, string.Format("确实要删除“{0}”吗?", this.Text), "确认图片删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                if (toolComboBoxExt.SelectedIndex > 0)
                    File.Delete(gridView.CurrentCell.ToolTipText);
                table.DefaultView.Delete(gridView.CurrentCellAddress.Y);
            }
        }
        #endregion

        #region InternetCacheImages
        private void toolComboBoxExt_SelectedIndexChanged(object sender, EventArgs e)
        {
            gridView.Focus();
            table.Clear();
            if (this.AllowDrop = (toolComboBoxExt.SelectedIndex == 0))
                return;
            table.BeginLoadData();
            string dirPath = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
            foreach (string filePath in Directory.GetFiles(dirPath, toolComboBoxExt.Text, SearchOption.AllDirectories))
            {
                table.Rows.Add(filePath, File.ReadAllBytes(filePath));
            }
            table.EndLoadData();
        }
        #endregion

        #region PaintImage
        private void toolButtonPaint_Click(object sender, EventArgs e)
        {
            using (Process psi = new Process())
            {
                psi.StartInfo.FileName = "mspaint.exe"; // 启动画图。
                psi.StartInfo.WorkingDirectory = Environment.SystemDirectory;
                psi.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
                psi.Start();
            }
        }
        #endregion

        #region RotateImage
        private void toolButtonLeft_Click(object sender, EventArgs e)
        {
            picture.Image.RotateFlip(RotateFlipType.Rotate90FlipXY); // 逆时针旋转图片90°。
            picture.Refresh(); // 刷新图片。
        }

        private void toolButtonRight_Click(object sender, EventArgs e)
        {
            picture.Image.RotateFlip(RotateFlipType.Rotate90FlipNone); // 顺时针旋转图片90°。
            picture.Refresh(); // 刷新图片。
        }
        #endregion

        #region SaveImage
        private void toolButtonSave_Click(object sender, EventArgs e)
        {
            Image img = picture.Image;
            img.Save("Image.png", img.RawFormat);
            Process.Start(Environment.CurrentDirectory);
            System.Threading.Thread.Sleep(300);
            SendKeys.SendWait("Image.png");
        }
        #endregion

        #region TimerInfo
        private void timerInfo_Tick(object sender, EventArgs e)
        {
            Application.CurrentCulture.ClearCachedData();
            DateTime solar = DateTime.Now;
            int month = lunarCalendar.GetMonth(solar);
            int leapMonth = lunarCalendar.GetLeapMonth(lunarCalendar.GetYear(solar));
            if (0 < leapMonth && leapMonth <= month)
                --month;
            statusLabelTime.Text = string.Format("{0:F} [{1} {2:00}]", solar, DateTimeFormatInfo.CurrentInfo.MonthNames[month - 1], lunarCalendar.GetDayOfMonth(solar));
        }
        #endregion
    }
}

原创粉丝点击