想在程序中添加一个按钮,点击后扫描出来图片,并在程序中显示,在网上查了大把资料,也下载了一个DEMO,但是都失败了,谁能给个能用的源程序,谢谢.
解决方案 »
- 问个支付宝接口的问题
- C# winform设计panel中嵌panel滚动问题求助~~~
- vs2008中文下载地址,要不用注册的。
- 谁可以给我讲解一下如何使用LINQ对数据库建模
- 捕获Ctrl按钮 释放的事件
- ^ō^ 寻求(反射).FieldInfo取值的优化方案...
- 如何判断当前窗口是否位于程序的最上层
- 关于DataTable的列求和的问题
- 请问在winform里面如何使用DotNetBar控件
- 新手求教:为什么我的循环有问题?
- 关于c#中文件的问题
- 应该这样用 C# 及 ExtJS实现:在页面中用GRID显示数据,实现:分组,分页,Grid右键快捷菜单(菜单可操作当前记录,如查看,修改,删除),数据用C#从MS SQL2005读取?
using System.Runtime.InteropServices;
using System.Windows.Forms;namespace ScanTool
{ public class TwProtocol
{ // TWON_PROTOCOL...
public const short Major = 1;
public const short Minor = 9;
}
[Flags]
internal enum TwDG : short
{ // DG_.....
Control = 0x0001,
Image = 0x0002,
Audio = 0x0004
} internal enum TwDAT : short
{ // DAT_....
Null = 0x0000,
Capability = 0x0001,
Event = 0x0002,
Identity = 0x0003,
Parent = 0x0004,
PendingXfers = 0x0005,
SetupMemXfer = 0x0006,
SetupFileXfer = 0x0007,
Status = 0x0008,
UserInterface = 0x0009,
XferGroup = 0x000a,
TwunkIdentity = 0x000b,
CustomDSData = 0x000c,
DeviceEvent = 0x000d,
FileSystem = 0x000e,
PassThru = 0x000f, ImageInfo = 0x0101,
ImageLayout = 0x0102,
ImageMemXfer = 0x0103,
ImageNativeXfer = 0x0104,
ImageFileXfer = 0x0105,
CieColor = 0x0106,
GrayResponse = 0x0107,
RGBResponse = 0x0108,
JpegCompression = 0x0109,
Palette8 = 0x010a,
ExtImageInfo = 0x010b, SetupFileXfer2 = 0x0301
} internal enum TwMSG : short
{ // MSG_.....
Null = 0x0000,
Get = 0x0001,
GetCurrent = 0x0002,
GetDefault = 0x0003,
GetFirst = 0x0004,
GetNext = 0x0005,
Set = 0x0006,
Reset = 0x0007,
QuerySupport = 0x0008, XFerReady = 0x0101,
CloseDSReq = 0x0102,
CloseDSOK = 0x0103,
DeviceEvent = 0x0104, CheckStatus = 0x0201, OpenDSM = 0x0301,
CloseDSM = 0x0302, OpenDS = 0x0401,
CloseDS = 0x0402,
UserSelect = 0x0403, DisableDS = 0x0501,
EnableDS = 0x0502,
EnableDSUIOnly = 0x0503, ProcessEvent = 0x0601, EndXfer = 0x0701,
StopFeeder = 0x0702, ChangeDirectory = 0x0801,
CreateDirectory = 0x0802,
Delete = 0x0803,
FormatMedia = 0x0804,
GetClose = 0x0805,
GetFirstFile = 0x0806,
GetInfo = 0x0807,
GetNextFile = 0x0808,
Rename = 0x0809,
Copy = 0x080A,
AutoCaptureDir = 0x080B, PassThru = 0x0901
}
internal enum TwRC : short
{ // TWRC_....
Success = 0x0000,
Failure = 0x0001,
CheckStatus = 0x0002,
Cancel = 0x0003,
DSEvent = 0x0004,
NotDSEvent = 0x0005,
XferDone = 0x0006,
EndOfList = 0x0007,
InfoNotSupported = 0x0008,
DataNotAvailable = 0x0009
} internal enum TwCC : short
{ // TWCC_....
Success = 0x0000,
Bummer = 0x0001,
LowMemory = 0x0002,
NoDS = 0x0003,
MaxConnections = 0x0004,
OperationError = 0x0005,
BadCap = 0x0006,
BadProtocol = 0x0009,
BadValue = 0x000a,
SeqError = 0x000b,
BadDest = 0x000c,
CapUnsupported = 0x000d,
CapBadOperation = 0x000e,
CapSeqError = 0x000f,
Denied = 0x0010,
FileExists = 0x0011,
FileNotFound = 0x0012,
NotEmpty = 0x0013,
PaperJam = 0x0014,
PaperDoubleFeed = 0x0015,
FileWriteError = 0x0016,
CheckDeviceOnline = 0x0017
}
internal enum TwOn : short
{ // TWON_....
Array = 0x0003,
Enum = 0x0004,
One = 0x0005,
Range = 0x0006,
DontCare = -1
} internal enum TwType : short
{ // TWTY_....
Int8 = 0x0000,
Int16 = 0x0001,
Int32 = 0x0002,
UInt8 = 0x0003,
UInt16 = 0x0004,
UInt32 = 0x0005,
Bool = 0x0006,
Fix32 = 0x0007,
Frame = 0x0008,
Str32 = 0x0009,
Str64 = 0x000a,
Str128 = 0x000b,
Str255 = 0x000c,
Str1024 = 0x000d,
Str512 = 0x000e
}
internal enum TwCap : short
{
XferCount = 0x0001, // CAP_XFERCOUNT
ICompression = 0x0100, // ICAP_...
IPixelType = 0x0101,
IUnits = 0x0102,
IXferMech = 0x0103
}
// ------------------- STRUCTS -------------------------------------------- [StructLayout(LayoutKind.Sequential, Pack=2, CharSet=CharSet.Ansi)]
internal class TwIdentity
{ // TW_IDENTITY
public IntPtr Id;
public TwVersion Version;
public short ProtocolMajor;
public short ProtocolMinor;
public int SupportedGroups;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=34)]
public string Manufacturer;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=34)]
public string ProductFamily;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=34)]
public string ProductName;
} [StructLayout(LayoutKind.Sequential, Pack=2, CharSet=CharSet.Ansi)]
internal struct TwVersion
{ // TW_VERSION
public short MajorNum;
public short MinorNum;
public short Language;
public short Country;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=34)]
public string Info;
} [StructLayout(LayoutKind.Sequential, Pack=2)]
internal class TwUserInterface
{ // TW_USERINTERFACE
public short ShowUI; // bool is strictly 32 bit, so use short
public short ModalUI;
public IntPtr ParentHand;
} [StructLayout(LayoutKind.Sequential, Pack=2)]
internal class TwStatus
{ // TW_STATUS
public short ConditionCode; // TwCC
public short Reserved;
} [StructLayout(LayoutKind.Sequential, Pack=2)]
internal struct TwEvent
{ // TW_EVENT
public IntPtr EventPtr;
public short Message;
}
[StructLayout(LayoutKind.Sequential, Pack=2)]
internal class TwImageInfo
{ // TW_IMAGEINFO
public int XResolution;
public int YResolution;
public int ImageWidth;
public int ImageLength;
public short SamplesPerPixel;
[MarshalAs( UnmanagedType.ByValArray, SizeConst=8)]
public short[] BitsPerSample;
public short BitsPerPixel;
public short Planar;
public short PixelType;
public short Compression;
} [StructLayout(LayoutKind.Sequential, Pack=2)]
internal class TwPendingXfers
{ // TW_PENDINGXFERS
public short Count;
public int EOJ;
}
[StructLayout(LayoutKind.Sequential, Pack=2)]
internal struct TwFix32
{ // TW_FIX32
public short Whole;
public ushort Frac;
public float ToFloat()
{
return (float) Whole + ( (float)Frac /65536.0f );
}
public void FromFloat( float f )
{
int i = (int)((f * 65536.0f) + 0.5f);
Whole = (short) (i >> 16);
Frac = (ushort) (i & 0x0000ffff);
}
} [StructLayout(LayoutKind.Sequential, Pack=2)]
internal class TwCapability
{ // TW_CAPABILITY
public TwCapability( TwCap cap )
{
Cap = (short) cap;
ConType = -1;
}
public TwCapability( TwCap cap, short sval )
{
Cap = (short) cap;
ConType = (short) TwOn.One;
Handle = Twain.GlobalAlloc( 0x42, 6 );
IntPtr pv = Twain.GlobalLock( Handle );
Marshal.WriteInt16( pv, 0, (short) TwType.Int16 );
Marshal.WriteInt32( pv, 2, (int) sval );
Twain.GlobalUnlock( Handle );
}
~TwCapability()
{
if( Handle != IntPtr.Zero )
Twain.GlobalFree( Handle );
}
public short Cap;
public short ConType;
public IntPtr Handle;
}
}// namespace TwainLib
using System.Collections;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace ScanTool
{ public delegate void ScanFinishedHandle(string file);
public delegate void ScanFinishedPointHandle(IntPtr bmpptr);
/// <summary>
/// ScanWrap 的摘要说明。
/// </summary>
public class ScanWrap:IMessageFilter
{ #region 成员变量
private bool msgfilter;
private Twain tw;
private Form m_Parent;
public ScanFinishedHandle ScanFinished;
public ScanFinishedPointHandle ScanFinishedPoint;
public bool IsGif = true;
public bool IsSave2File = true;
#endregion public ScanWrap(Form frm)
{
m_Parent = frm;
InitTwain();
} public void Dispose()
{
if(tw != null)
{
tw.Finish();
tw = null;
}
} public void StartScan()
{
if( Twain.ScreenBitDepth < 15 )
{
MessageBox.Show( "显示器需要设置为真彩色!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information );
return;
} if( !msgfilter )
{
m_Parent.Enabled = false;
msgfilter = true;
Application.AddMessageFilter(this);
}
tw.Acquire();
} public void SelectScanner()
{
tw.Select();
} private void InitTwain()
{
if(tw == null)
{
tw = new Twain();
tw.Init(m_Parent.Handle);
tw.Failed = new FailedHandle(Failed);
}
} private void Failed()
{
EndingScan();
} #region IMessageFilter 成员 public bool PreFilterMessage(ref Message m)
{
TwainCommand cmd = tw.PassMessage(ref m );
if( cmd == TwainCommand.Not )
return false; switch(cmd)
{
case TwainCommand.CloseRequest:
{
EndingScan();
tw.CloseSrc();
break;
}
case TwainCommand.CloseOk:
{
EndingScan();
tw.CloseSrc();
break;
}
case TwainCommand.DeviceEvent:
{
break;
}
case TwainCommand.TransferReady:
{
ArrayList pics = tw.TransferPictures();
EndingScan();
tw.CloseSrc();
// picnumber++;
// int picnum;
for( int i = 0; i < pics.Count; i++ )
{
IntPtr img = (IntPtr) pics[ i ];
if(IsSave2File)
Save2File(img);
else if(ScanFinishedPoint != null)
ScanFinishedPoint(img);
// PicForm newpic = new PicForm( img );
// newpic.MdiParent = this;
// picnum = i + 1;
// newpic.Text = "ScanPass" + picnumber.ToString() + "_Pic" + picnum.ToString();
// newpic.Show();
}
break;
}
}
return true;
} private void EndingScan()
{
if(msgfilter)
{
Application.RemoveMessageFilter(this);
msgfilter = false;
m_Parent.Enabled = true;
m_Parent.Activate();
}
}
private void Save2File(IntPtr img)
{
IntPtr bmpptr = Win32API.GlobalLock(img);
bool monochrome = false;
IntPtr pixptr = GetPixelInfo(bmpptr,ref monochrome);
string file = "";
bool bRtn = Gdip.SaveDIBAs(file,bmpptr,pixptr );
if(bRtn && ScanFinished != null)
ScanFinished(file);
Win32API.GlobalFree(img);
img = IntPtr.Zero;
bmpptr = IntPtr.Zero;
pixptr = IntPtr.Zero;
} /// <summary>
/// 得到位图的像素信息
/// </summary>
/// <param name="bmpptr"></param>
/// <returns></returns>
private IntPtr GetPixelInfo(IntPtr bmpptr,ref bool monochrome)
{
BITMAPINFOHEADER bmi = new BITMAPINFOHEADER();
Marshal.PtrToStructure(bmpptr,bmi); if( bmi.biSizeImage == 0 )
bmi.biSizeImage = ((((bmi.biWidth * bmi.biBitCount) + 31) & ~31) >> 3) * bmi.biHeight; int p = bmi.biClrUsed;
if( (p == 0) && (bmi.biBitCount <= 8) )
p = 1 << bmi.biBitCount;
monochrome = (bmi.biBitCount == 1);
p = (p * 4) + bmi.biSize + (int) bmpptr;
return (IntPtr)p;
} #endregion
}
}///end ScanWrap
using System.Text;
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;namespace ScanTool
{
public class Gdip
{
#region 成员变量
private static ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
// private const string TEMPPATH = @"\TEMPPICFILE";
// private const string DEFAULTIMAGEFILE = "Temp";
// private const string DEFAULTIMAGEEXT = ".JPG";
#endregion private static bool GetCodecClsid( string filename, out Guid clsid )
{
clsid = Guid.Empty;
string ext = Path.GetExtension( filename );
if( ext == null )
return false;
ext = "*" + ext.ToUpper();
foreach( ImageCodecInfo codec in codecs )
{
if( codec.FilenameExtension.IndexOf( ext ) >= 0 )
{
clsid = codec.Clsid;
return true;
}
}
return false;
} /// <summary>
///
/// </summary>
/// <param name="picname"></param>
/// <param name="bminfo"></param>
/// <param name="pixdat"></param>
/// <returns></returns>
public static bool SaveDIBAs( string picname, IntPtr bminfo, IntPtr pixdat )
{
Guid clsid;
if( ! GetCodecClsid( picname, out clsid ) )
{
MessageBox.Show( "未知的图形扩展名" + Path.GetExtension( picname ),
"Image Codec", MessageBoxButtons.OK, MessageBoxIcon.Information );
return false;
}
IntPtr img = IntPtr.Zero;
int st = Win32API.GdipCreateBitmapFromGdiDib( bminfo, pixdat, ref img );
if( (st != 0) || (img == IntPtr.Zero) )
return false; st = Win32API.GdipSaveImageToFile( img, picname, ref clsid, IntPtr.Zero );
// GetCodecClsid( file, out clsid );
// Win32API.GdipSaveImageToFile( img, file, ref clsid, IntPtr.Zero );
Win32API.GdipDisposeImage( img );
return st == 0;
}
}
} // namespace GdiPlusLib
using System.Runtime.InteropServices;
using System.Windows.Forms;namespace ScanTool
{ public class TwProtocol
{ // TWON_PROTOCOL...
public const short Major = 1;
public const short Minor = 9;
}
[Flags]
internal enum TwDG : short
{ // DG_.....
Control = 0x0001,
Image = 0x0002,
Audio = 0x0004
} internal enum TwDAT : short
{ // DAT_....
Null = 0x0000,
Capability = 0x0001,
Event = 0x0002,
Identity = 0x0003,
Parent = 0x0004,
PendingXfers = 0x0005,
SetupMemXfer = 0x0006,
SetupFileXfer = 0x0007,
Status = 0x0008,
UserInterface = 0x0009,
XferGroup = 0x000a,
TwunkIdentity = 0x000b,
CustomDSData = 0x000c,
DeviceEvent = 0x000d,
FileSystem = 0x000e,
PassThru = 0x000f, ImageInfo = 0x0101,
ImageLayout = 0x0102,
ImageMemXfer = 0x0103,
ImageNativeXfer = 0x0104,
ImageFileXfer = 0x0105,
CieColor = 0x0106,
GrayResponse = 0x0107,
RGBResponse = 0x0108,
JpegCompression = 0x0109,
Palette8 = 0x010a,
ExtImageInfo = 0x010b, SetupFileXfer2 = 0x0301
} internal enum TwMSG : short
{ // MSG_.....
Null = 0x0000,
Get = 0x0001,
GetCurrent = 0x0002,
GetDefault = 0x0003,
GetFirst = 0x0004,
GetNext = 0x0005,
Set = 0x0006,
Reset = 0x0007,
QuerySupport = 0x0008, XFerReady = 0x0101,
CloseDSReq = 0x0102,
CloseDSOK = 0x0103,
DeviceEvent = 0x0104, CheckStatus = 0x0201, OpenDSM = 0x0301,
CloseDSM = 0x0302, OpenDS = 0x0401,
CloseDS = 0x0402,
UserSelect = 0x0403, DisableDS = 0x0501,
EnableDS = 0x0502,
EnableDSUIOnly = 0x0503, ProcessEvent = 0x0601, EndXfer = 0x0701,
StopFeeder = 0x0702, ChangeDirectory = 0x0801,
CreateDirectory = 0x0802,
Delete = 0x0803,
FormatMedia = 0x0804,
GetClose = 0x0805,
GetFirstFile = 0x0806,
GetInfo = 0x0807,
GetNextFile = 0x0808,
Rename = 0x0809,
Copy = 0x080A,
AutoCaptureDir = 0x080B, PassThru = 0x0901
}
internal enum TwRC : short
{ // TWRC_....
Success = 0x0000,
Failure = 0x0001,
CheckStatus = 0x0002,
Cancel = 0x0003,
DSEvent = 0x0004,
NotDSEvent = 0x0005,
XferDone = 0x0006,
EndOfList = 0x0007,
InfoNotSupported = 0x0008,
DataNotAvailable = 0x0009
} internal enum TwCC : short
{ // TWCC_....
Success = 0x0000,
Bummer = 0x0001,
LowMemory = 0x0002,
NoDS = 0x0003,
MaxConnections = 0x0004,
OperationError = 0x0005,
BadCap = 0x0006,
BadProtocol = 0x0009,
BadValue = 0x000a,
SeqError = 0x000b,
BadDest = 0x000c,
CapUnsupported = 0x000d,
CapBadOperation = 0x000e,
CapSeqError = 0x000f,
Denied = 0x0010,
FileExists = 0x0011,
FileNotFound = 0x0012,
NotEmpty = 0x0013,
PaperJam = 0x0014,
PaperDoubleFeed = 0x0015,
FileWriteError = 0x0016,
CheckDeviceOnline = 0x0017
}
internal enum TwOn : short
{ // TWON_....
Array = 0x0003,
Enum = 0x0004,
One = 0x0005,
Range = 0x0006,
DontCare = -1
} internal enum TwType : short
{ // TWTY_....
Int8 = 0x0000,
Int16 = 0x0001,
Int32 = 0x0002,
UInt8 = 0x0003,
UInt16 = 0x0004,
UInt32 = 0x0005,
Bool = 0x0006,
Fix32 = 0x0007,
Frame = 0x0008,
Str32 = 0x0009,
Str64 = 0x000a,
Str128 = 0x000b,
Str255 = 0x000c,
Str1024 = 0x000d,
Str512 = 0x000e
}
internal enum TwCap : short
{
XferCount = 0x0001, // CAP_XFERCOUNT
ICompression = 0x0100, // ICAP_...
IPixelType = 0x0101,
IUnits = 0x0102,
IXferMech = 0x0103
}
// ------------------- STRUCTS -------------------------------------------- [StructLayout(LayoutKind.Sequential, Pack=2, CharSet=CharSet.Ansi)]
internal class TwIdentity
{ // TW_IDENTITY
public IntPtr Id;
public TwVersion Version;
public short ProtocolMajor;
public short ProtocolMinor;
public int SupportedGroups;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=34)]
public string Manufacturer;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=34)]
public string ProductFamily;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=34)]
public string ProductName;
} [StructLayout(LayoutKind.Sequential, Pack=2, CharSet=CharSet.Ansi)]
internal struct TwVersion
{ // TW_VERSION
public short MajorNum;
public short MinorNum;
public short Language;
public short Country;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=34)]
public string Info;
} [StructLayout(LayoutKind.Sequential, Pack=2)]
internal class TwUserInterface
{ // TW_USERINTERFACE
public short ShowUI; // bool is strictly 32 bit, so use short
public short ModalUI;
public IntPtr ParentHand;
} [StructLayout(LayoutKind.Sequential, Pack=2)]
internal class TwStatus
{ // TW_STATUS
public short ConditionCode; // TwCC
public short Reserved;
} [StructLayout(LayoutKind.Sequential, Pack=2)]
internal struct TwEvent
{ // TW_EVENT
public IntPtr EventPtr;
public short Message;
}
[StructLayout(LayoutKind.Sequential, Pack=2)]
internal class TwImageInfo
{ // TW_IMAGEINFO
public int XResolution;
public int YResolution;
public int ImageWidth;
public int ImageLength;
public short SamplesPerPixel;
[MarshalAs( UnmanagedType.ByValArray, SizeConst=8)]
public short[] BitsPerSample;
public short BitsPerPixel;
public short Planar;
public short PixelType;
public short Compression;
} [StructLayout(LayoutKind.Sequential, Pack=2)]
internal class TwPendingXfers
{ // TW_PENDINGXFERS
public short Count;
public int EOJ;
}
[StructLayout(LayoutKind.Sequential, Pack=2)]
internal struct TwFix32
{ // TW_FIX32
public short Whole;
public ushort Frac;
public float ToFloat()
{
return (float) Whole + ( (float)Frac /65536.0f );
}
public void FromFloat( float f )
{
int i = (int)((f * 65536.0f) + 0.5f);
Whole = (short) (i >> 16);
Frac = (ushort) (i & 0x0000ffff);
}
} [StructLayout(LayoutKind.Sequential, Pack=2)]
internal class TwCapability
{ // TW_CAPABILITY
public TwCapability( TwCap cap )
{
Cap = (short) cap;
ConType = -1;
}
public TwCapability( TwCap cap, short sval )
{
Cap = (short) cap;
ConType = (short) TwOn.One;
Handle = Twain.GlobalAlloc( 0x42, 6 );
IntPtr pv = Twain.GlobalLock( Handle );
Marshal.WriteInt16( pv, 0, (short) TwType.Int16 );
Marshal.WriteInt32( pv, 2, (int) sval );
Twain.GlobalUnlock( Handle );
}
~TwCapability()
{
if( Handle != IntPtr.Zero )
Twain.GlobalFree( Handle );
}
public short Cap;
public short ConType;
public IntPtr Handle;
}
}// namespace TwainLib
private ScanWrap m_ScanWrap;
private void btnScan_Click(object sender, System.EventArgs e)
{ m_ScanWrap.StartScan();
} #endregion #region 选择扫描仪 private void btnSelect_Click(object sender, System.EventArgs e)
{
m_ScanWrap.SelectScanner();
}
我看Photoshop中就可以调用扫描仪程序,然后扫描,把图片返回到PS的窗口