65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 C# 从您的应用程序调用“打开方式”对话框

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.31/5 (30投票s)

2006 年 2 月 17 日

CPOL

2分钟阅读

viewsIcon

141741

downloadIcon

1780

本文演示了如何使用 C# 从您的应用程序调用“打开方式”对话框。

摘要

本文旨在向 .NET 初学者介绍使用 C# 进行 Shell 编程。Shell 命名空间将文件系统和其他由 Shell 管理的对象组织成单个树状结构层次。从概念上讲,Shell 命名空间本质上是文件系统的更大更全面的版本。Shell 命名空间对象包括文件系统文件夹和文件,以及“虚拟”对象,例如回收站和打印机文件夹。Shell 的主要职责之一是管理和提供对构成系统的各种对象的访问。在这里,我创建了一个示例,演示如何在您的 Windows 系统中调用“打开方式”对话框。

解决方案概述

在本文中,我开发了一个简单的图像查看器应用程序,以演示在 Windows 中使用 C# 调用“打开方式”对话框。Shell 概念确实很难解释。该应用程序是使用 Microsoft Visual C# Express Edition 开发的。

此应用程序中使用的控件

private System.Windows.Forms.Button btnBrowseImg;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
public System.Windows.Forms.PictureBox pictureBox1;

此应用程序中使用的命名空间

using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Drawing;

带有代码的解决方案

结构体声明包含可选的属性集,可选的结构体修饰符集,后跟关键字 struct 和命名该结构体的标识符,后跟可选的结构体接口规范,后跟结构体主体,最后可选地以分号结尾。Serializable 关键字指示可以序列化一个类。此类不能被继承。

// 
[Serializable]
public struct ShellExecuteInfo
{
    public int Size;
    public uint Mask;
    public IntPtr hwnd;
    public string Verb;
    public string File;
    public string Parameters;
    public string Directory;
    public uint Show;
    public IntPtr InstApp;
    public IntPtr IDList;
    public string Class;
    public IntPtr hkeyClass;
    public uint HotKey;
    public IntPtr Icon;
    public IntPtr Monitor;
}

// Code For OpenWithDialog Box
[DllImport("shell32.dll", SetLastError = true)]
extern public static bool 
       ShellExecuteEx(ref ShellExecuteInfo lpExecInfo);

public const uint SW_NORMAL = 1;

static void OpenAs(string file)
{
    ShellExecuteInfo sei = new ShellExecuteInfo();
    sei.Size = Marshal.SizeOf(sei);
    sei.Verb = "openas";
    sei.File = file;
    sei.Show = SW_NORMAL;
    if (!ShellExecuteEx(ref sei))
        throw new System.ComponentModel.Win32Exception();
}

示例工作原理

运行示例代码,单击“浏览”按钮并选择要在查看器中查看的图像,然后单击“确定”。图像将显示在图像查看器工具中。然后,如果您想在其他图像处理程序(如 Photoshop、ImageReady 等)中查看相同的图像,只需单击该图像即可,将打开“打开方式”对话框,您可以在其中选择任何您喜欢的工具。这就是示例代码的工作方式。

参考文献

© . All rights reserved.