【C#】WindowsAPICodePackで、各種ファイルのサムネイルを表示してみる。
おはようございます。
Windowsフォームに画像を表示するのに、
画像ファイルであれば特に何も考えずに表示できますが、
それ以外のファイルでサムネイルを表示する方法を試してみました。
プログラムは新規で、新たにプロジェクトを作成します。
スポンサーリンク
新規プロジェクトの作成
VisualStudio2017で新しく WindowsForm プロジェクトを作成します。
今回は「SampleThumbnailView」としました。
画面の作成

画面にラベル、テキストボックス、ボタン、ピクチャーボックスを並べます。
パッケージの追加
ファイルからサムネイルを作るために、別途パッケージをインストールします。

ソリューションエクスプローラーで、「参照」を右クリック>「NuGetパッケージの管理」メニューを選択します。

WindowsAPICodePackを入力、表示された「Microsoft-WindowsAPICodePack-Shell」をインストールします。

変更のプレビューが表示される場合は「OK」ボタンをクリックします。
プログラム
Form1.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; usingSystem.Windows.Forms; usingSystem.IO; usingMicrosoft.WindowsAPICodePack.Shell; namespaceSampleThumbnailView { /// <summary> /// メイン画面 /// </summary> publicpartial classForm1:Form { /// <summary> /// 画面表示時の処理 /// </summary> publicForm1() { InitializeComponent(); } /// <summary> /// 参照ボタンクリックイベント. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> privatevoidbtn_ref_Click(objectsender,EventArgse) { OpenFileDialog ofd=newOpenFileDialog(); ofd.InitialDirectory=System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop); ofd.Filter="すべてのファイル(*.*)|*.*"; ofd.FilterIndex=2; ofd.Title="開くファイルを選択してください"; ofd.RestoreDirectory=true; ofd.CheckFileExists=true; ofd.CheckPathExists=true; //ダイアログを表示する if(ofd.ShowDialog()==DialogResult.OK) { //OKボタンがクリックされたとき、選択されたファイル名を表示する txb_file.Text=ofd.FileName; } } /// <summary> /// 表示ボタンクリックイベント. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> privatevoidbtn_read_Click(objectsender,EventArgse) { pcb_preview.Image=CreateThumbnail(txb_file.Text,1); } /// <summary> /// サムネイル画像を生成します. /// </summary> /// <param name="path"></param> /// <param name="scale"></param> /// <returns></returns> privateBitmap CreateThumbnail(stringpath,intscale) { // ファイルが存在した場合 FileInfo fi=newFileInfo(path); if(fi.Exists) { ShellFile shellFile=ShellFile.FromFilePath(path); Bitmap bmp=shellFile.Thumbnail.Bitmap; intw=(int)(bmp.Width*scale); inth=(int)(bmp.Height*scale); returnbmp; } // ファイルが存在しない場合はデフォルト表示 returnSampleThumbnailView.Properties.Resources.Message; } } } |
起動してみる

初期表示、「参照」ボタンをクリックします。

今回は試しに Json ファイルを指定してみます。

サムネイルが表示されました。

存在しないファイルを指定した場合

デフォルトの画像を表示(エラー)するようにしてみました。
まとめ
単発のネタです。(多分)
あまり利用シーンは少ないかもしれませんが、何かのお役に立てれば。
ではでは。
ソースはこちら。
ディスカッション
コメント一覧
AcrobatReaderDCの「Windows Explorer で PDF サムネールのプレビューを有効にする」を有効活用出来ました。
https://helpx.adobe.com/jp/acrobat/using/enable-pdf-thumbnail-preview-windows-explorer.html
バグってる。
NAS上のPDF群を一覧させると、2個目が1個目のイメージになり、以降全てずれている。
非同期完了待ち絡みでも、追跡してみるかな・・・