C# - 使用键盘快捷键快速打开图片文件

时间:2011-11-03 11:49:04

标签: image key

我正在试图弄清楚如何编写代码以便在我的小程序中快速打开PNG文件。这是场景:

  • 我有多个图片文件,比如PNG,在多个文件夹中(与程序在同一个根目录中)。
  • 我希望能够回忆起这些图片,并尽可能少地按键显示它们,希望不需要鼠标。

然后,当程序处于活动状态时,我希望能够

  1. 按一个键让程序知道我想加载一个新文件,说“O”;
  2. 键入两位数的文件夹名称,例如“LL”和
  3. 输入两位数的文件名,例如“05”(假设扩展名为“.png”)
  4. 程序打开/LL/05.png文件并全屏显示
  5. 我已经能够进行“预定”的图片显示,并打开了一个“打开文件对话框”,但不是我在这里谈论的直接方法。

1 个答案:

答案 0 :(得分:1)

我的解决方案并不完美,需要进行大量额外检查 无论如何,它是您需求的起点 首先在表单上设置KeyPreview = true 然后使用:

public partial class Form1 : Form
{
    private bool reading = false;
    private byte dirSize = 2;
    private byte filesize = 2;
    private string keys = "";
    private const string defExt = ".png";
    private string exePath = 
        Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.O)
        {
            reading = true;
            keys = "";
            e.Handled = true;
            return;
        }

        if (reading)
        {
            Char ch = (char)(e.KeyValue);
            if (Char.IsLetterOrDigit(ch))
            {
                keys += ch;
                e.Handled = true;
            }
            if (keys.Length == (dirSize + filesize))
            {
                string dir = Path.Combine(exePath, keys.Substring(0, dirSize));
                string filename = keys.Substring(dirSize, filesize) + defExt;
                string fullPath = Path.Combine(dir, filename);
                if (File.Exists(fullPath))
                    pictureBox1.Image = Image.FromFile(fullPath);
                reading = false;
            }
        }
    }
}
相关问题