2008년 9월 18일 목요일

C# SAMPLE

VC#のサンプルプログラムです。
情報源 メーリングリストや他のHP
No 名前 作成日時
01 LHA書庫ファイルの中身を見る 2002/11/20
02 ZIP圧縮 2002/11/21
03 ZIP書庫ファイルの中身を見る< 2002/11/23
04 RARの解凍 2002/11/23
05 ファイルパスからアイコンを取り出す 2002/11/23
06 Enumサンプル 2002/11/29
07 Parse 2002/12/09
08 画像表示 2003/06/30
09 UnZipExtractMem 2003/06/30
10 Enum.Parse 2003/07/01

LHA書庫ファイルの中身を見る

フォームにドロップしたLHA書庫ファイルの中身を見ます。

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Text;
using System.Runtime.InteropServices;



namespace LHA_e
{
///
/// Form1 の概要の説明です。
///

public class Form1 : System.Windows.Forms.Form
{
public const int FNAME_MAX32 = 512;
[ StructLayout( LayoutKind.Sequential )]
public struct INDIVIDUALINFO
{
System.UInt32 dwOriginalSize; /* ファイルのサイズ */
System.UInt32 dwCompressedSize; /* 圧縮後のサイズ */
System.UInt32 dwCRC; /* 格納ファイルのチェックサム */
System.UInt32 uFlag; /* 処理結果 */
/* Status flag */
System.UInt32 uOSType; /* 書庫作成に使われた OS */
System.UInt16 wRatio; /* 圧縮率 */
System.UInt16 wDate; /* 格納ファイルの日付(DOS 形式) */
System.UInt16 wTime; /* 格納ファイルの時刻(〃) */
[ MarshalAs( UnmanagedType.ByValTStr, SizeConst=FNAME_MAX32 + 1 )]
string szFileName; /* 書庫名 */
[ MarshalAs( UnmanagedType.ByValTStr, SizeConst=3 )]
string dummy1;
[ MarshalAs( UnmanagedType.ByValTStr, SizeConst=8 )]
string szAttribute; /* 格納ファイルの属性(書庫固有) */
[ MarshalAs( UnmanagedType.ByValTStr, SizeConst=8 )]
string szMode; /* 格納ファイルの格納モード(〃) */
}

[DllImport("UNLHA32", CharSet=CharSet.Ansi )]
public static extern IntPtr UnlhaOpenArchive(IntPtr _hwnd, string _szFileName,
System.UInt32 _dwMode);
[DllImport("UNLHA32", CharSet=CharSet.Ansi )]
public static extern System.Int32 UnlhaFindFirst(IntPtr _harc, string _szWildName,
ref INDIVIDUALINFO lpSubInfo);

[DllImport("UNLHA32", CharSet=CharSet.Ansi )]
public static extern System.Int32 UnlhaFindNext(IntPtr _harc, ref INDIVIDUALINFO lpSubInfo);

[DllImport("UNLHA32", CharSet=CharSet.Ansi )]
public static extern System.Int32 UnlhaGetFileName(IntPtr _harc, StringBuilder _lpBuffer, int _nsize);

[DllImport("UNLHA32", CharSet=CharSet.Ansi )]
public static extern System.Int32 UnlhaCloseArchive(IntPtr _harc);

private System.Windows.Forms.ListView listView1;
private System.Windows.Forms.ColumnHeader columnHeader1;
///
/// 必要なデザイナ変数です。
///

private System.ComponentModel.Container components = null;

public Form1()
{
//
// Windows フォーム デザイナ サポートに必要です。
//
InitializeComponent();

//
// TODO: InitializeComponent 呼び出しの後に、コンストラクタ コードを追加してください。
//
}

///
/// 使用されているリソースに後処理を実行します。
///

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
///
/// デザイナ サポートに必要なメソッドです。このメソッドの内容を
/// コード エディタで変更しないでください。
///

private void InitializeComponent()
{
this.listView1 = new System.Windows.Forms.ListView();
this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
this.SuspendLayout();
//
// listView1
//
this.listView1.AllowDrop = true;
this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1});
this.listView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(292, 273);
this.listView1.TabIndex = 0;
this.listView1.View = System.Windows.Forms.View.Details;
this.listView1.DragDrop += new System.Windows.Forms.DragEventHandler(this.listView1_DragDrop);
this.listView1.DragEnter += new System.Windows.Forms.DragEventHandler(this.listView1_DragEnter);
this.listView1.SelectedIndexChanged += new System.EventHandler(this.listView1_SelectedIndexChanged);
//
// columnHeader1
//
this.columnHeader1.Text = "FileName";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 12);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.listView1});
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);

}
#endregion

///
/// アプリケーションのメイン エントリ ポイントです。
///

[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private void listView1_SelectedIndexChanged(object sender, System.EventArgs e)
{

}

private void Form1_Load(object sender, System.EventArgs e)
{

}

private void listView1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
e.Effect = DragDropEffects.Copy | DragDropEffects.Move;
}

private void listView1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
IDataObject dataObject;
dataObject = e.Data;
string [] paths =(string[])dataObject.GetData(DataFormats.FileDrop);

IntPtr harc = UnlhaOpenArchive(this.Handle, paths[0], 0);

INDIVIDUALINFO info = new INDIVIDUALINFO();
StringBuilder wildname = new StringBuilder();


if (UnlhaFindFirst(harc, "*.*", ref info) != -1)
{
listView1.Items.Clear();
do
{
StringBuilder filename2 = new StringBuilder(256);
UnlhaGetFileName(harc, filename2, 256);
listView1.Items.Add(filename2.ToString());
} while (UnlhaFindNext(harc, ref info) != -1);
UnlhaCloseArchive(harc);
}
}
}
}


ZIP圧縮

フォームにドロップしたファイルを圧縮します。

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
using System.Text;

namespace Zip32J_r
{
///
/// Form1 の概要の説明です。
///

public class Form1 : System.Windows.Forms.Form
{
[DllImport("ZIP32J.DLL", CharSet=CharSet.Ansi )]
public static extern long Zip (IntPtr hwnd,string szCmdLine, StringBuilder SzOutput, int dwSize);

///
/// 必要なデザイナ変数です。
///

private System.ComponentModel.Container components = null;

public Form1()
{
//
// Windows フォーム デザイナ サポートに必要です。
//
InitializeComponent();

//
// TODO: InitializeComponent 呼び出しの後に、コンストラクタ コードを追加してください。
//
}

///
/// 使用されているリソースに後処理を実行します。
///

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
///
/// デザイナ サポートに必要なメソッドです。このメソッドの内容を
/// コード エディタで変更しないでください。
///

private void InitializeComponent()
{
//
// Form1
//
this.AllowDrop = true;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 12);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.Form1_DragDrop);
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.Form1_DragEnter);

}
#endregion

///
/// アプリケーションのメイン エントリ ポイントです。
///

[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private void Form1_Load(object sender, System.EventArgs e)
{

}

private void Form1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
e.Effect = DragDropEffects.Copy | DragDropEffects.Move;
}

private void Form1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
IDataObject dataObject;
dataObject = e.Data;
string [] paths =(string[])dataObject.GetData(DataFormats.FileDrop);

string response_file_path = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
response_file_path = response_file_path + @"\" + "response.lst";

System.IO.Stream stream = System.IO.File.Open(response_file_path, System.IO.FileMode.Create);
System.IO.StreamWriter writer = new System.IO.StreamWriter(stream, System.Text.Encoding.GetEncoding("shift_jis"));

foreach(string a_filepath in paths)
{
writer.WriteLine(@"""" + a_filepath + @"""");
}

writer.Close();
stream.Close();

string makefilepath = System.IO.Path.GetDirectoryName(paths[0]) + @"\" +
System.IO.Path.GetFileNameWithoutExtension(paths[0]);

string cmdline;
StringBuilder output = new StringBuilder(256);
cmdline = @"-r """ + makefilepath + @""" @" + response_file_path;

long i = Zip(this.Handle, cmdline, output, 256);

}
}
}


ZIP書庫ファイルの中身を見る

フォームにドロップした書庫ファイルの中身をみます。

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Text;
using System.Runtime.InteropServices;


namespace zip_e
{
///
/// Form1 の概要の説明です。
///

public class Form1 : System.Windows.Forms.Form
{
public const int FNAME_MAX32 = 512;

public struct INDIVIDUALINFO
{
System.UInt32 dwOriginalSize; /* ファイルのサイズ */
System.UInt32 dwCompressedSize; /* 圧縮後のサイズ */
System.UInt32 dwCRC; /* 格納ファイルのチェックサム */
System.UInt32 uFlag; /* 処理結果 */
/* Status flag */
System.UInt32 uOSType; /* 書庫作成に使われた OS */
System.UInt16 wRatio; /* 圧縮率 */
System.UInt16 wDate; /* 格納ファイルの日付(DOS 形式) */
System.UInt16 wTime; /* 格納ファイルの時刻(〃) */
[ MarshalAs( UnmanagedType.ByValTStr, SizeConst = FNAME_MAX32 + 1 )]
string szFileName; /* 書庫名 */
[ MarshalAs( UnmanagedType.ByValTStr, SizeConst=3 )]
string dummy1;
[ MarshalAs( UnmanagedType.ByValTStr, SizeConst=8 )]
string szAttribute; /* 格納ファイルの属性(書庫固有) */
[ MarshalAs( UnmanagedType.ByValTStr, SizeConst=8 )]
string szMode; /* 格納ファイルの格納モード(〃) */
}

[DllImport("UNZIP32", CharSet=CharSet.Ansi )]
public static extern IntPtr UnZipOpenArchive(IntPtr _hwnd, string _szFileName, System.UInt32 _dwMode);

[DllImport("UNZIP32", CharSet=CharSet.Ansi )]
public static extern System.Int32 UnZipFindFirst(IntPtr _harc, string _szWildName,
ref INDIVIDUALINFO lpSubInfo);

[DllImport("UNZip32", CharSet=CharSet.Ansi )]
public static extern System.Int32 UnZipGetFileName(IntPtr _harc, StringBuilder _lpBuffer, int _nsize);

[DllImport("UNZip32", CharSet=CharSet.Ansi )]
public static extern System.Int32 UnZipCloseArchive(IntPtr _harc);


[DllImport("UNZIP32", CharSet=CharSet.Ansi )]
public static extern System.Int32 UnZipFindNext(IntPtr _harc, ref INDIVIDUALINFO lpSubInfo);


///
/// 必要なデザイナ変数です。
///


private System.Windows.Forms.ListView listView1;
private System.Windows.Forms.ColumnHeader columnHeader1; System.ComponentModel.Container components = null;

public Form1()
{
//
// Windows フォーム デザイナ サポートに必要です。
//
InitializeComponent();

//
// TODO: InitializeComponent 呼び出しの後に、コンストラクタ コードを追加してください。
//
}

///
/// 使用されているリソースに後処理を実行します。
///

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
///
/// デザイナ サポートに必要なメソッドです。このメソッドの内容を
/// コード エディタで変更しないでください。
///

private void InitializeComponent()
{
this.listView1 = new System.Windows.Forms.ListView();
this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
this.SuspendLayout();
//
// listView1
//
this.listView1.AllowDrop = true;
this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1});
this.listView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(292, 273);
this.listView1.TabIndex = 0;
this.listView1.View = System.Windows.Forms.View.Details;
this.listView1.DragDrop += new System.Windows.Forms.DragEventHandler(this.listView1_DragDrop);
this.listView1.DragEnter += new System.Windows.Forms.DragEventHandler(this.listView1_DragEnter);
this.listView1.SelectedIndexChanged += new System.EventHandler(this.listView1_SelectedIndexChanged);
//
// columnHeader1
//
this.columnHeader1.Text = "FileName";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 12);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.listView1});
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);

}
#endregion

///
/// アプリケーションのメイン エントリ ポイントです。
///

[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private void Form1_Load(object sender, System.EventArgs e)
{

}

private void listView1_SelectedIndexChanged(object sender, System.EventArgs e)
{

}

private void listView1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
e.Effect = DragDropEffects.Copy | DragDropEffects.Move;
}

private void listView1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
IDataObject dataObject;
dataObject = e.Data;
string [] paths =(string[])dataObject.GetData(DataFormats.FileDrop);

IntPtr harc = UnZipOpenArchive(this.Handle, paths[0], 0);

INDIVIDUALINFO info = new INDIVIDUALINFO();
StringBuilder wildname = new StringBuilder();


if (UnZipFindFirst(harc, "*.*", ref info) != -1)
{
listView1.Items.Clear();
do
{
StringBuilder filename2 = new StringBuilder(256);
UnZipGetFileName(harc, filename2, 256);
listView1.Items.Add(filename2.ToString());
} while (UnZipFindNext(harc, ref info) != -1);
UnZipCloseArchive(harc);
}

}
}
}


RARの解凍

フォームにドロップした書庫ファイルを解凍します。

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
using System.Text;

namespace Zip32J_r
{
///
/// Form1 の概要の説明です。
///
public class Form1 : System.Windows.Forms.Form
{
[DllImport("UNRAR32.DLL", CharSet=CharSet.Ansi )]
public static extern long Unrar (IntPtr hwnd, string szCmdLine, StringBuilder SzOutput, int dwSize);

///
/// 必要なデザイナ変数です。
///
private System.ComponentModel.Container components = null;

public Form1()
{
//
// Windows フォーム デザイナ サポートに必要です。
//
InitializeComponent();

//
// TODO: InitializeComponent 呼び出しの後に、コンストラクタ コードを追加してください。
//
}

///
/// 使用されているリソースに後処理を実行します。
///
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
///
/// デザイナ サポートに必要なメソッドです。このメソッドの内容を
/// コード エディタで変更しないでください。
///
private void InitializeComponent()
{
//
// Form1
//
this.AllowDrop = true;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 12);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.Form1_DragDrop);
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.Form1_DragEnter);

}
#endregion

///
/// アプリケーションのメイン エントリ ポイントです。
///
[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private void Form1_Load(object sender, System.EventArgs e)
{

}

private void Form1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
e.Effect = DragDropEffects.Copy | DragDropEffects.Move;
}

private void Form1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
IDataObject dataObject;
dataObject = e.Data;
string path =((string[])dataObject.GetData(DataFormats.FileDrop))[0];
string cmdline;

StringBuilder output = new StringBuilder(256);
cmdline = @"-x """ + path + @"""";

long i = Unrar(this.Handle, cmdline, output, 256);
}
}
}


ファイルパスからアイコンを取り出す

フォームにドロップしたファイルからファイルパスとアイコンを表示します。
ListView1のViewプロパティを変更すると大きいアイコンと小さいアイコンが、
割り当てられていることが解ります。
APIはよくわからないので、これが正しい書き方かどうかは解りません。
アドバイスをお願いします。

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;

namespace sample
{

///
/// Form1 の概要の説明です。
///
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.ListView listView1;
private System.Windows.Forms.ColumnHeader columnHeader1;

const int LVM_SETIMAGELIST = 0x1003;

enum LVSIL
{
LVSIL_NORMAL = 0x0000,
LVSIL_SMALL = 0x0001,
LVSIL_STATE = 0x0002
}

#region SHFILEINFO

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
public struct SHFILEINFO
{
public IntPtr hIcon;
public int iIcon;
public int dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=80)]
public string szTypeName;
}

#endregion

#region ListViewItem flags

public enum ListViewItemFlags
{
LVIF_TEXT = 0x0001,
LVIF_IMAGE = 0x0002,
LVIF_PARAM = 0x0004,
LVIF_STATE = 0x0008,
LVIF_INDENT = 0x0010,
LVIF_NORECOMPUTE = 0x0800
}

#endregion

#region ListView Messages

public enum ListViewMessages
{
LVM_FIRST = 0x1000,
LVM_SETITEM = (LVM_FIRST + 06),
LVM_GETSUBITEMRECT = (LVM_FIRST + 56),
LVM_GETITEMSTATE = (LVM_FIRST + 44),
LVM_GETITEMTEXTW = (LVM_FIRST + 115)
}

#endregion

#region LVITEM

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
public struct LVITEM
{
public ListViewItemFlags mask;
public int iItem;
public int iSubItem;
public int state;
public int stateMask;
public IntPtr pszText;
public int cchTextMax;
public int iImage;
public int lParam;
public int iIndent;
}

#endregion

#region Shell File Info Flags

public enum ShellFileInfoFlags
{
SHGFI_ICON = 0x000000100,
SHGFI_DISPLAYNAME = 0x000000200,
SHGFI_TYPENAME = 0x000000400,
SHGFI_ATTRIBUTES = 0x000000800,
SHGFI_ICONLOCATION = 0x000001000,
SHGFI_EXETYPE = 0x000002000,
SHGFI_SYSICONINDEX = 0x000004000,
SHGFI_LINKOVERLAY = 0x000008000,
SHGFI_SELECTED = 0x000010000,
SHGFI_ATTR_SPECIFIED = 0x000020000,
SHGFI_LARGEICON = 0x000000000,
SHGFI_SMALLICON = 0x000000001,
SHGFI_OPENICON = 0x000000002,
SHGFI_SHELLICONSIZE = 0x000000004,
SHGFI_PIDL = 0x000000008,
SHGFI_USEFILEATTRIBUTES = 0x000000010
}

#endregion

class WindowsAPI
{
#region Shell32.dll functions

[DllImport("Shell32.dll", CharSet=CharSet.Auto)]
public static extern IntPtr SHGetFileInfo(string drivePath, int fileAttributes,
out SHFILEINFO fileInfo, int countBytesFileInfo, ShellFileInfoFlags flags);

#endregion

#region User32.dll functions

[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern int SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);
[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern void SendMessage(IntPtr hWnd, ListViewMessages msg, int wParam, ref LVITEM lParam);

#endregion
}
///
/// 必要なデザイナ変数です。
///
private System.ComponentModel.Container components = null;

public Form1()
{
//
// Windows フォーム デザイナ サポートに必要です。
//
InitializeComponent();

//
// TODO: InitializeComponent 呼び出しの後に、コンストラクタ コードを追加してください。
//
}

///
/// 使用されているリソースに後処理を実行します。
///
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
///
/// デザイナ サポートに必要なメソッドです。このメソッドの内容を
/// コード エディタで変更しないでください。
///
private void InitializeComponent()
{
this.listView1 = new System.Windows.Forms.ListView();
this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
this.SuspendLayout();
//
// listView1
//
this.listView1.AllowDrop = true;
this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1});
this.listView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(292, 273);
this.listView1.TabIndex = 0;
this.listView1.View = System.Windows.Forms.View.SmallIcon;
this.listView1.DragDrop += new System.Windows.Forms.DragEventHandler(this.listView1_DragDrop);
this.listView1.DragEnter += new System.Windows.Forms.DragEventHandler(this.listView1_DragEnter);
//
// columnHeader1
//
this.columnHeader1.Text = "名前";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 12);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.listView1});
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);

}
#endregion

///
/// アプリケーションのメイン エントリ ポイントです。
///
[STAThread]
static void Main()
{
Application.Run(new Form1());
}





private void Form1_Load(object sender, System.EventArgs e)
{
SHFILEINFO shfi = new SHFILEINFO();
IntPtr hSystemImageList = IntPtr.Zero;

hSystemImageList = WindowsAPI.SHGetFileInfo(@"c:\", 0, out shfi, Marshal.SizeOf(typeof(SHFILEINFO)),
ShellFileInfoFlags.SHGFI_SYSICONINDEX | ShellFileInfoFlags.SHGFI_SMALLICON );
WindowsAPI.SendMessage(listView1.Handle, LVM_SETIMAGELIST, (int)LVSIL.LVSIL_SMALL, (int)hSystemImageList);
hSystemImageList = WindowsAPI.SHGetFileInfo(@"c:\", 0, out shfi, Marshal.SizeOf(typeof(SHFILEINFO)),
ShellFileInfoFlags.SHGFI_SYSICONINDEX | ShellFileInfoFlags.SHGFI_LARGEICON );
WindowsAPI.SendMessage(listView1.Handle, LVM_SETIMAGELIST, (int)LVSIL.LVSIL_NORMAL, (int)hSystemImageList);
}

private void SetupListViewItem(ref LVITEM item, string filePath)
{
SHFILEINFO shfi = new SHFILEINFO();
item.mask = ListViewItemFlags.LVIF_IMAGE;
WindowsAPI.SHGetFileInfo(filePath, 0, out shfi, Marshal.SizeOf(typeof(SHFILEINFO)),
ShellFileInfoFlags.SHGFI_SYSICONINDEX | ShellFileInfoFlags.SHGFI_SMALLICON | ShellFileInfoFlags.SHGFI_LARGEICON);
item.iImage = shfi.iIcon;
}

void SetItem(System.Windows.Forms.ListView listView, ref LVITEM item)
{
WindowsAPI.SendMessage(listView.Handle, ListViewMessages.LVM_SETITEM,0,ref item);
}

private void listView1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
IDataObject dataObject = e.Data;

bool flag = false;
foreach(string format in dataObject.GetFormats())
{
if (format == DataFormats.FileDrop)
{
flag = true;
}
}

if (flag == false)
return;

e.Effect = DragDropEffects.Copy | DragDropEffects.Move;
}

private void listView1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
IDataObject dataObject = e.Data;

bool flag = false;
foreach(string format in dataObject.GetFormats())
{
if (format == DataFormats.FileDrop)
{
flag = true;
}
}

if (flag == false)
return;

this.listView1.Items.Clear();
foreach(string path in (string[])dataObject.GetData(DataFormats.FileDrop))
{
InsertItem(path);
}
}

private void InsertItem(string filePath)
{
ListViewItem item;
LVITEM item2 = new LVITEM();

item = listView1.Items.Add(filePath);

SetupListViewItem(ref item2, filePath);
item2.iItem = item.Index;
SetItem(listView1, ref item2);
}
}
}


Enumサンプル

Enumのサンプルです。
[FlagsAttribute]宣言つ付けるか付けないかで結果が変わります。

using System;

namespace ConsoleApplication1
{
///
/// Class1 の概要の説明です。
///

class Class1
{
[FlagsAttribute]
enum TestEnum
{
a = 0x01,
b = 0x02,
c = 0x04
}
///
/// アプリケーションのメイン エントリ ポイントです。
///

[STAThread]
static void Main(string[] args)
{
TestEnum testEnum;

string [] names = Enum.GetNames(typeof(Class1.TestEnum));

foreach(string name in names)
{
Console.WriteLine(name);
}

testEnum = TestEnum.a | TestEnum.b;
Console.WriteLine(testEnum);
//
// TODO: アプリケーションを開始するコードをここに追加してください。
//
}
}
}


Parse

文字列から数値にキャストするときに使います。
boolにもParseがあります。iniファイルにtrueまたはfalseを書き込みそれを読み込んだ
りする時に重宝しています

using System;

namespace ConsoleApplication1
{
///
/// Class1 の概要の説明です。
///

class Class1
{
///
/// アプリケーションのメイン エントリ ポイントです。
///

[STAThread]
static void Main(string[] args)
{
int i1 = 100;
int i2 = int.Parse(i1.ToString());
bool bl1 = true;
bool bl2 = bool.Parse(bl1.ToString());
//
// TODO: アプリケーションを開始するコードをここに追加してください。
//
}
}
}


画像表示

宇宙仮面さんの「ImageViewerを作る」を元に、表示しきれない画像はスクロール
させる機能を追加しました。

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace ImageView
{
///
/// Form1 の概要の説明です。
///
public class Form1 : System.Windows.Forms.Form
{
private System.Drawing.Image image;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuItem2;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.VScrollBar vScrollBar1;
private System.Windows.Forms.HScrollBar hScrollBar1;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
///
/// 必要なデザイナ変数です。
///
private System.ComponentModel.Container components = null;

public Form1()
{
//
// Windows フォーム デザイナ サポートに必要です。
//
InitializeComponent();

//
// TODO: InitializeComponent 呼び出しの後に、コンストラクタ コードを追加してください。
//
}

///
/// 使用されているリソースに後処理を実行します。
///
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
///
/// デザイナ サポートに必要なメソッドです。このメソッドの内容を
/// コード エディタで変更しないでください。
///
private void InitializeComponent()
{
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.vScrollBar1 = new System.Windows.Forms.VScrollBar();
this.hScrollBar1 = new System.Windows.Forms.HScrollBar();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.SuspendLayout();
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem1});
//
// menuItem1
//
this.menuItem1.Index = 0;
this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem2});
this.menuItem1.Text = "ファイル";
//
// menuItem2
//
this.menuItem2.Index = 0;
this.menuItem2.Text = "開く";
this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click);
//
// pictureBox1
//
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(272, 248);
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
this.pictureBox1.Click += new System.EventHandler(this.pictureBox1_Click);
this.pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint);
//
// vScrollBar1
//
this.vScrollBar1.Location = new System.Drawing.Point(272, 0);
this.vScrollBar1.Name = "vScrollBar1";
this.vScrollBar1.Size = new System.Drawing.Size(16, 248);
this.vScrollBar1.TabIndex = 1;
this.vScrollBar1.ValueChanged += new System.EventHandler(this.vScrollBar1_ValueChanged);
//
// hScrollBar1
//
this.hScrollBar1.Location = new System.Drawing.Point(0, 248);
this.hScrollBar1.Name = "hScrollBar1";
this.hScrollBar1.Size = new System.Drawing.Size(272, 16);
this.hScrollBar1.TabIndex = 2;
this.hScrollBar1.ValueChanged += new System.EventHandler(this.hScrollBar1_ValueChanged);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 12);
this.ClientSize = new System.Drawing.Size(288, 265);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.hScrollBar1,
this.vScrollBar1,
this.pictureBox1});
this.Menu = this.mainMenu1;
this.Name = "Form1";
this.Text = "Form1";
this.Resize += new System.EventHandler(this.Form1_Resize);
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);

}
#endregion

///
/// アプリケーションのメイン エントリ ポイントです。
///
[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private void Form1_Load(object sender, System.EventArgs e)
{

}

private void pictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
this.DrawImage(e.Graphics);
}

private void Form1_Resize(object sender, System.EventArgs e)
{
ReSize();
}

private void ReSize()
{
System.Drawing.Graphics g;
System.Drawing.Size size = this.ClientSize;

if (image == null)
{
this.vScrollBar1.Visible = false;
this.hScrollBar1.Visible = false;
return;
}

if (size.Width >= this.image.Width)
{
this.pictureBox1.Height = size.Height;
this.hScrollBar1.Visible = false;
}
else
{
this.pictureBox1.Height = size.Height - this.hScrollBar1.Height;
this.hScrollBar1.Maximum = 0;
this.hScrollBar1.Minimum = 0;
this.hScrollBar1.Visible = true;
}

if (size.Height >= this.image.Height)
{
this.pictureBox1.Width = size.Width;
this.vScrollBar1.Visible = false;
}
else
{
this.pictureBox1.Width = size.Width - this.vScrollBar1.Width;
this.vScrollBar1.Maximum = 0;
this.vScrollBar1.Minimum = 0;
this.vScrollBar1.Visible = true;
}

this.hScrollBar1.Maximum = this.image.Width - this.pictureBox1.Width + 10 - 1;
this.vScrollBar1.Maximum = this.image.Height - this.pictureBox1.Height + 10 - 1;

//this.hScrollBar1.LargeChange = 10;
//this.vScrollBar1.LargeChange = 10;

this.vScrollBar1.Left = this.pictureBox1.Width;
this.vScrollBar1.Height = this.pictureBox1.Height;
this.hScrollBar1.Top = this.pictureBox1.Height;
this.hScrollBar1.Width = this.pictureBox1.Width;

g = System.Drawing.Graphics.FromHwnd(this.pictureBox1.Handle);
this.DrawImage(g);
}

private void pictureBox1_Click(object sender, System.EventArgs e)
{

}

private void menuItem2_Click(object sender, System.EventArgs e)
{
System.Windows.Forms.DialogResult result = this.openFileDialog1.ShowDialog();
try
{
this.image = System.Drawing.Image.FromFile(this.openFileDialog1.FileName);
ReSize();
}
catch (Exception exception)
{
System.Windows.Forms.MessageBox.Show(exception.ToString());
}
}

private void DrawImage(Graphics g)
{
if (image == null)
{
return;
}

Point[] points = new Point[3];
Rectangle rectangle = new Rectangle();
rectangle.Width = image.Width;
rectangle.Height = image.Height;

if (this.hScrollBar1.Visible == false)
{
rectangle.X = 0;
}
else
{
rectangle.X = this.hScrollBar1.Value;
}
if (this.vScrollBar1.Visible == false)
{
rectangle.Y = 0;
}
else
{
rectangle.Y = this.vScrollBar1.Value;
}

points[0].X = 0;
points[0].Y = 0;
points[1].X = image.Width;
points[1].Y = 0;
points[2].X = 0;
points[2].Y = image.Height;

g.DrawImage(image, points, rectangle, GraphicsUnit.Pixel);
}

private void vScrollBar1_ValueChanged(object sender, System.EventArgs e)
{
System.Drawing.Graphics g;

g = System.Drawing.Graphics.FromHwnd(this.pictureBox1.Handle);
this.DrawImage(g);
}

private void hScrollBar1_ValueChanged(object sender, System.EventArgs e)
{
System.Drawing.Graphics g;

g = System.Drawing.Graphics.FromHwnd(this.pictureBox1.Handle);
this.DrawImage(g);
}
}
}


UnZipExtractMem

test/test2.jpgを含む複数のファイルを圧縮したアーカイブの中のtest2.jpgだけを
メモリーに解凍するサンプルです。
lpwAttrが取得できなかったので、不完全です。

using System;
using System.Runtime.InteropServices;


namespace UnZipExtractMem
{
///
/// Class1 の概要の説明です。
///

class Class1
{
[DllImport("UNZIP32", CharSet=CharSet.Ansi )]
public static extern System.Int32 UnZipExtractMem(IntPtr hWnd,
string szCmdLine,
byte[] szBuffer,
System.UInt32 dwSize,
ref System.Int32 lpTime,
IntPtr lpwAttr,
ref System.UInt32 lpdwWriteSize
);

///
/// アプリケーションのメイン エントリ ポイントです。
///

[STAThread]
static void Main(string[] args)
{
string szCmdLine;
byte[] szBuffer = new byte[100];
System.UInt32 dwSize = 100;
System.Int32 lpTime = new System.Int32();
System.UInt16 lpwAttr = new System.UInt16();
System.UInt32 lpdwWriteSize = new System.UInt32();

szCmdLine = @"c:\test.ZIP test/test2.jpg";

System.Int32 int32 = new System.Int32();

UnZipExtractMem((System.IntPtr)null, szCmdLine, szBuffer, dwSize, ref lpTime, (System.IntPtr)null, ref lpdwWriteSize);

//
// TODO: アプリケーションを開始するコードをここに追加してください。
//

}
}
}


Enum.Parse

Enum.Parseの使い方です。

using System;

namespace Enum
{
///
/// Class1 の概要の説明です。
///

class Class1
{
enum TestEnum
{
a,
b,
c
};
///
/// アプリケーションのメイン エントリ ポイントです。
///

[STAThread]
static void Main(string[] args)
{
TestEnum testEnum;

testEnum = (TestEnum)System.Enum.Parse(typeof(TestEnum), "a");

//
// TODO: アプリケーションを開始するコードをここに追加してください。
//
}
}
}

ayrun님의 블로그 :: 네이버 블로그

ayrun님의 블로그 :: 네이버 블로그

2008년 9월 17일 수요일

탑~! 블로그 - ADO.NET DB연결 문자열

[C#]
ADO.NET DB연결 문자열 - System.Data.SqlClient
www.wssplex.net

SQL Server .NET Data Provider
System.Data.SqlClient
Using C#:

using System.Data.SqlClient;
...
SqlConnection oSQLConn = new SqlConnection();
oSQLConn.ConnectionString = "Data Source=(local);" +
"Initial Catalog=myDatabaseName;" +
"Integrated Security=SSPI";
oSQLConn.Open();


Using VB.NET:

Imports System.Data.SqlClient
...
Dim oSQLConn As SqlConnection = New SqlConnection()
oSQLConn.ConnectionString = "Data Source=(local);" & _
"Initial Catalog=myDatabaseName;" & _
"Integrated Security=SSPI"
oSQLConn.Open()


원격서버 IP 연결:

oSQLConn.ConnectionString = "Network Library=DBMSSOCN;" & _
"Data Source=xxx.xxx.xxx.xxx,1433;" & _
"Initial Catalog=myDatabaseName;" & _
"User ID=myUsername;" & _
"Pas sword=myPassword"


* TCP/IP 연결시, Network Library=DBMSSOCN. 암호화시 Encrypt=yes


연결시 선택가능한 네트워크 프로토콜:

Name Network library
dbnmpntw Win32 Named Pipes *
dbmssocn Win32 Winsock TCP/IP *
dbmsspxn Win32 SPX/IPX
dbmsvinn Win32 Banyan Vines
dbmsrpcn Win32 Multi-Protocol (Windows RPC) *


좀더 자세한 사항은 MSDN 을 참조하세요.
1. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ado270/htm/mdrefsqlprovspec.asp

2. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ado270/htm/mdmscadoproperties.asp


ADO.NET DB연결 문자열 - Oracle.DataAccess.Client
www.wssplex.net

Oracle .NET Data Provider - From Oracle
Oracle.DataAccess.Client

using Oracle.DataAccess.Client;
...
OracleConnection oOracleConn = new OracleConnection();
oOracleConn.ConnectionString = "Data Source=MyOracleServerName;" +
"Integrated Security=SSPI";
oOracleConn.Open();

* 오라클에서 제공하는 드라이버를 이용하는 경우입니다.

ADO.NET DB연결 문자열 - System.Data.OracleClient
www.wssplex.net

Oracle .NET Data Provider - From Microsoft
System.Data.OracleClient

using System.Data.OracleClient;

OracleConnection oOracleConn = new OracleConnection();
oOracleConn.ConnectionString = "Data Source=Oracle8i;" +
"Integrated Security=SSPI";
oOracleConn.Open();


*오라클 클라이언트가 최소한 8.1.7 이상은 설치되어야 합니다.

ADO.NET DB연결 문자열 - System.Data.OleDb
www.wssplex.net

For IBM AS/400 OLE DB Provider

' VB.NET
Imports System.Data.OleDb
...
Dim oOleDbConnection As OleDbConnection
Dim sConnString As String = _
"Provider=IBMDA400.DataSource.1;" & _
"Data source=myAS400DbName;" & _
"User Id=myUsername;" & _
"Password=myPassword"
oOleDbConnection = New OleDb.OleDbConnection(sConnString)
oOleDbConnection.Open()

For JET OLE DB Provider

' VB.NET
Imports System.Data.OleDb
...
Dim oOleDbConnection As OleDbConnection
Dim sConnString As String = _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\myPath\myJet.mdb;" & _
"User ID=Admin;" & _
"Password="
oOleDbConnection = New OleDb.OleDbConnection(sConnString)
oOleDbConnection.Open()

For Oracle OLE DB Provider

' VB.NET
Imports System.Data.OleDb
...
Dim oOleDbConnection As OleDbConnection
Dim sConnString As String = _
"Provider=OraOLEDB.Oracle;" & _
"Data Source=MyOracleDB;" & _
"User ID=myUsername;" & _
"Password=myPassword"
oOleDbConnection = New OleDb.OleDbConnection(sConnString)
oOleDbConnection.Open()

For SQL Server OLE DB Provider

' VB.NET
Imports System.Data.OleDb
...
Dim oOleDbConnection As OleDbConnection
Dim sConnString As String = _
"Provider=sqloledb;" & _
"Data Source=myServerName;" & _
"Initial Catalog=myDatabaseName;" & _
"User Id=myUsername;" & _
"Password=myPassword"
oOleDbConnection = New OleDb.OleDbConnection(sConnString)
oOleDbConnection.Open()


For Sybase ASE OLE DB Provider

' VB.NET
Imports System.Data.OleDb
...
Dim oOleDbConnection As OleDbConnection
Dim sConnString As String = _
"Provider=Sybase ASE OLE DB Provider;" & _
"Data Source=MyDataSourceName;" & _
"Server Name=MyServerName;" & _
"Database=MyDatabaseName;" & _
"User ID=myUsername;" & _
"Password=myPassword"
oOleDbConnection = New OleDb.OleDbConnection(sConnString)
oOleDbConnection.Open()

ADO.NET DB연결 문자열 - System.Data.ODBC
www.wssplex.net

For SQL Server ODBC Driver

' VB.NET
Imports System.Data.Odbc
...
Dim oODBCConnection As OdbcConnection
Dim sConnString As String = _
"Driver={SQL Server};" & _
"Server=MySQLServerName;" & _
"Database=MyDatabaseName;" & _
"Uid=MyUsername;" & _
"Pwd=MyPassword"
oODBCConnection = New Odbc.OdbcConnection(sConnString)
oODBCConnection.Open()

For Oracle ODBC Driver

' VB.NET
Imports System.Data.Odbc
...
Dim oODBCConnection As OdbcConnection
Dim sConnString As String = _
"Driver={Microsoft ODBC for Oracle};" & _
"Server=OracleServer.world;" & _
"Uid=myUsername;" & _
"Pwd=myPassword"
oODBCConnection = New Odbc.OdbcConnection(sConnString)
oODBCConnection.Open()

For Access (JET) ODBC Driver

' VB.NET
Imports System.Data.Odbc
...
Dim oODBCConnection As OdbcConnection
Dim sConnString As String = _
"Driver={Microsoft Access Driver (*.mdb)};" & _
"Dbq=c:\somepath\mydb.mdb;" & _
"Uid=Admin;" & _
"Pwd="
oODBCConnection = New Odbc.OdbcConnection(sConnString)
oODBCConnection.Open()

For Sybase System 11 ODBC Driver

' VB.NET
Imports System.Data.Odbc
...
Dim oODBCConnection As OdbcConnection
Dim sConnString As String = _
"Driver={Sybase System 11};" & _
"SRVR=mySybaseServerName;" & _
"DB=myDatabaseName;" & _
"UID=myUsername;" & _
"PWD=myPassword"
oODBCConnection = New OdbcConnection(sConnString)
oODBCConnection.Open()

For all other ODBC Drivers

' VB.NET
Imports System.Data.Odbc
...
Dim oODBCConnection As OdbcConnection
Dim sConnString As String = "Dsn=myDsn;" & _
"Uid=myUsername;" & _
"Pwd=myPassword"
oODBCConnection = New Odbc.OdbcConnection(sConnString)
oODBCConnection.Open()

ADO.NET DB연결 문자열 - CoreLab.MySql
www.wssplex.net

MySQLDirect .NET Data Provider
CoreLab.MySql


using CoreLab.MySql;

MySqlConnection oMySqlConn = new MySqlConnection();
oMySqlConn.ConnectionString = "User ID=myUsername;" +
"Password=myPassword;" +
"Host=localhost;" +
"Port=3306;" +
"Database=myDatabaseName;" +
"Direct=true;" +
"Protocol=TCP;" +
"Compress=false;" +
"Pooling=true;" +
"Min Pool Size=0;" +
"Max Pool Size=100;" +
"Connection Lifetime=0";
oMySqlConn.Open();


[드라이버컴포넌트 다운로드]


ADO.NET DB연결 문자열 - Sybase.Data.AseClient
www.wssplex.net

Adaptive Server Enterprise (ASE) .NET Data Provider
Sybase.Data.AseClient

using Sybase.Data.AseClient;
...
AseConnection oAseConn = new AseConnection();
oAseConn.ConnectionString = "Data Source=(local);" +
"Initial Catalog=myDatabaseName;" +
"User ID=myUsername;" +
"Password=myPassword"
oAseConn.Open();