C# 检索IE缓存图片

来源:互联网 发布:网络教学和函授 编辑:程序博客网 时间:2024/05/21 06:21
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Win32;

namespace BrowserImage
{
    static class Program
    {
        #region DllImportAttribute
        [DllImport("user32.dll", EntryPoint = "ShowWindow")]
        static extern bool ShowWindow(IntPtr handle, int flags);

        [DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
        static extern bool SetForegroundWindow(IntPtr handle);
        #endregion

        [STAThread]
        static void Main()
        {
            #region Mutex
            bool isCreated; // 互斥体名称须唯一。
            using (Mutex newMutex = new Mutex(true, @"Local\IEImage", out isCreated))
            {
                if (isCreated)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    using (RegistryKey subKey = Application.UserAppDataRegistry)
                    {
                        FormImage frame = new FormImage();
                        subKey.SetValue("Handle", frame.Handle);
                        Application.Run(frame);
                    }
                    newMutex.ReleaseMutex(); // 释放互斥体的所属权。
                }
                else
                {
                    string text = string.Format("“{0}”应用程序已经运行。", AppDomain.CurrentDomain.FriendlyName);
                    MessageBox.Show(text, "系统提示!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    using (RegistryKey subKey = Application.UserAppDataRegistry)
                    {
                        IntPtr handle = new IntPtr(Convert.ToInt32(subKey.GetValue("Handle")));
                        ShowWindow(handle, 1);
                        SetForegroundWindow(handle);
                    }
                    Application.ExitThread(); // 退出当前线程上的消息循环,并关闭该线程上的所有窗口。
                }
            }
            #endregion
        }
    }
}

using System;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
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("Image");
            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.Items.AddRange(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 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.AllowUserToResizeRows = false; // 禁用调整行的大小。
            gridView.AllowUserToResizeColumns = false; // 禁用调整列的大小。
            gridView.RowHeadersVisible = false; // 隐藏行标题。
            gridView.ColumnHeadersVisible = false; // 隐藏列标题。
            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);
            bool flag = (picture.Image != null);
            toolButtonCopy.Enabled = flag;
            toolButtonSave.Enabled = flag;
            toolButtonPaint.Enabled = flag;
        }

        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)
            {
                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(); // 清除所有数据。
            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)
        {
            Image img = picture.Image;
            img.Save("Image.png", img.RawFormat);
            Process.Start("mspaint.exe", "Image.png");
        }
        #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("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
    }
}

原创粉丝点击