일부 이미지 파일에는 이미지의 특성을 확인하는 데 사용할 수 있는 메타데이터가 있습니다. 예를 들어, 디지털 사진에 포함된 메타데이터를 분석하면 사진 촬영에 사용한 카메라의 제조업체와 모델을 알 수 있습니다. GDI+에서는 기존 메타데이터를 읽을 수 있을 뿐 아니라 이미지 파일에 새 메타데이터를 쓸 수도 있습니다.

GDI+에서는 개별 메타데이터를 PropertyItem 개체에 저장합니다. Image 개체의 PropertyItems 속성을 읽어 파일에 있는 모든 메타데이터를 검색할 수 있습니다. PropertyItems 속성은 PropertyItem 개체 배열을 반환합니다.

PropertyItem 개체에는 Id, Value, LenType이라는 네 가지 속성이 있습니다.

Id

메타데이터 항목을 식별하는 태그입니다. Id에 할당할 수 있는 값 중 일부가 다음 표에 나와 있습니다.

16진수 값
설명

0x0320

0x010F

0x0110

0x9003

0x829A

0x5090

0x5091

이미지 타이틀

장비 제조업체

장비 모델

ExifDTOriginal

Exif 노출 시간

광도 테이블

색소 테이블

Value

값 배열입니다. 값의 형식은 Type 속성에 따라 결정됩니다.

Len

Value 속성이 가리키는 값 배열의 바이트 단위 길이입니다.

Type

Value 속성이 가리키는 배열에 있는 값의 데이터 형식입니다. Type 속성 값이 나타내는 형식이 다음 표에 나와 있습니다.

숫자 값
설명

1

Byte입니다.

2

ASCII로 인코딩된 Byte 개체의 배열입니다.

3

16비트 정수입니다.

4

32비트 정수입니다.

5

유리수를 나타내는 Byte 개체 두 개로 이루어진 배열입니다.

6

사용되지 않습니다.

7

정의되어 있지 않습니다.

8

사용되지 않습니다.

9

SLong

10

SRational

예제

<?XML:NAMESPACE PREFIX = [default] http://ddue.schemas.microsoft.com/authoring/2003/5 NS = "http://ddue.schemas.microsoft.com/authoring/2003/5" />

설명

다음 코드 예제에서는 FakePhoto.jpg 파일에 있는 일곱 가지 메타데이터를 읽고 화면에 표시합니다. 목록에서 두 번째(인덱스 1)

속성 항목의 Id는 0x010F(장비 제조업체)이고 Type은 2(ASCII로 인코딩된 바이트 배열)입니다. 코드 예제에서는 해당 속성

항목의 값을 표시합니다.

코드를 실행하면 아래와 비슷한 결과가 나타납니다.

Property Item 0

id: 0x320

type: 2

length: 16 bytes

Property Item 1

id: 0x10f

type: 2

length: 17 bytes

Property Item 2

id: 0x110

type: 2

length: 7 bytes

Property Item 3

id: 0x9003

type: 2

length: 20 bytes

Property Item 4

id: 0x829a

type: 5

length: 8 bytes

Property Item 5

id: 0x5090

type: 3

length: 128 bytes

Property Item 6

id: 0x5091

type: 3

length: 128 bytes

The equipment make is Northwind Camera.

 

C#

// Create an Image object. 
Image image = new Bitmap("c:\FakePhoto.jpg");

// Get the PropertyItems property from image.
PropertyItem[] propItems = image.PropertyItems; 

// Set up the display.
Font font = new Font("Arial", 12);
SolidBrush blackBrush = new SolidBrush(Color.Black);
int X = 0;
int Y = 0;

// For each PropertyItem in the array, display the ID, type, and 
// length.
int count = 0;
foreach (PropertyItem propItem in propItems)
{
   e.Graphics.DrawString(
   "Property Item " + count.ToString(),
   font,
   blackBrush,
   X, Y);
   
   Y += font.Height;

   e.Graphics.DrawString(
      "   iD: 0x" + propItem.Id.ToString("x"),
      font,
      blackBrush,
      X, Y);

   Y += font.Height;

   e.Graphics.DrawString(
      "   type: " + propItem.Type.ToString(),
      font,
      blackBrush,
      X, Y);

   Y += font.Height;

   e.Graphics.DrawString(
      "   length: " + propItem.Len.ToString() + " bytes",
      font,
      blackBrush,
      X, Y);

   Y += font.Height;

   count++;
}
// Convert the value of the second property to a string, and display 
// it.
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
string manufacturer = encoding.GetString(propItems[1].Value);

e.Graphics.DrawString(
   "The equipment make is " + manufacturer + ".",
   font,
   blackBrush,
   X, Y);

코드 컴파일

앞의 예제는 Windows Forms에서 사용해야 하며 Paint 이벤트 처리기의 매개 변수인 PaintEventArgs e를 필요로 합니다. FakePhoto.jpg를 시스템에서 사용할 수 있는 이미지 이름 및 경로로 바꾸십시오.

참고 항목

기타 리소스
이미지, 비트맵 및 메타파일
이미지, 비트맵 및 메타파일 사용

ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.ko/dv_fxmclignrl/html/72ec0b31-0be7-444a-9575-1dbcb864e0be.htm

Visual C# 언어 개념

코드: 인쇄 미리 보기로 폼 보기(Visual C#)

이 예제에서는 현재 폼의 복사본을 인쇄 미리 보기로 보는 방법을 보여 줍니다.

예제
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern long BitBlt (IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop);
private Bitmap memoryImage;
private void CaptureScreen()
{
   Graphics mygraphics = this.CreateGraphics();
   Size s = this.Size;
   memoryImage = new Bitmap(s.Width, s.Height, mygraphics);
   Graphics memoryGraphics = Graphics.FromImage(memoryImage);
   IntPtr dc1 = mygraphics.GetHdc();
   IntPtr dc2 = memoryGraphics.GetHdc();
   BitBlt(dc2, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height, dc1, 0, 0, 13369376);
   mygraphics.ReleaseHdc(dc1);
   memoryGraphics.ReleaseHdc(dc2);
}
private void printDocument1_PrintPage(System.Object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
   e.Graphics.DrawImage(memoryImage, 0, 0);
}
private void printButton_Click(System.Object sender, System.EventArgs e)
{
   CaptureScreen();
   printPreviewDialog1.Show();
}
코드 컴파일

이 예제를 컴파일하려면 다음이 필요합니다.

  • PrintPage 이벤트 처리기가 있는 printDocument1이라는 PrintDocument 구성 요소
  • Document 속성이 printDocument1로 설정된 printPreviewDialog1이라는 PrintPreviewDialog 구성 요소
  • Click 이벤트 처리기가 있는 printButton이라는 Button 컨트롤

예제 코드가 기존의 이벤트 처리기를 대체합니다. printButton을 클릭하면 폼의 인쇄 미리 보기가 표시됩니다.

강력한 프로그래밍

다음의 경우에는 예외가 발생합니다.

  • 프린터에 액세스할 수 있는 권한이 없는 경우
  • 관리되지 않는 코드를 사용할 수 있는 권한이 없는 경우
  • 프린터가 설치되어 있지 않은 경우
  • 인쇄 미리 보기 대화 상자가 이미 사라진 경우 (인쇄 미리 보기 대화 상자를 닫은 경우)
보안

이 예제를 실행하려면 관리되지 않는 코드를 실행할 수 있는 권한과 프린터에 액세스할 수 있는 권한이 있어야 합니다.

참고 항목

그래픽 프로그래밍 예제 항목 | PrintDocument 구성 요소를 사용하여 인쇄 | GDI+를 사용하여 이미지 렌더링 | Windows Forms에서 그래픽 인쇄 | PrintDocument 클래스

Using the Save method to save images

private void SaveFileMenu_Click(object sender,
    System.EventArgs e)
{
    // If image is created
    if(curImage == null)
        return;
    // Call SaveFileDialog
    SaveFileDialog saveDlg = new SaveFileDialog();
    saveDlg.Title = "Save Image As";
    saveDlg.OverwritePrompt = true;
    saveDlg.CheckPathExists = true;
    saveDlg.Filter =
        "Bitmap File(*.bmp)|*.bmp|" +
        "Gif File(*.gif)|*.gif|" +
        "JPEG File(*.jpg)|*.jpg|" +
        "PNG File(*.png)|*.png" ;
    saveDlg.ShowHelp = true;
    // If selected, save
    if(saveDlg.ShowDialog() == DialogResult.OK)
    {
        // Get the user-selected file name
        string fileName = saveDlg.FileName;
        // Get the extension
        string strFilExtn =
            fileName.Remove(0, fileName.Length - 3);
        // Save file
        switch(strFilExtn)
        {
            case "bmp":
                curImage.Save(fileName, ImageFormat.Bmp);
                break;
            case "jpg":
                curImage.Save(fileName, ImageFormat.Jpeg);
                break;
            case "gif":
                curImage.Save(fileName, ImageFormat.Gif);
                break;
            case "tif":
                curImage.Save(fileName, ImageFormat.Tiff);
                break;
            case "png":
                curImage.Save(fileName, ImageFormat.Png);
                break;
            default:
                break;
            }
    }
}

Creating a Bitmap Object

The Bitmap class provides about a dozen overloaded forms of the constructors. You can create a Bitmap object from a bitmap file, or from Image, Stream, string, or Type objects. When you create a Bitmap object, you can also specify the size of the bitmap, the resolution of the Graphics object, and the pixel format of the bitmap.

The code snippet in Listing 7.17 creates Bitmap objects from an Image and file name with or without the size of the Bitmap included.

Listing 7.17 Creating Bitmap objects from different sources
// Creating an Image object
Image curImage = Image.FromFile("myfile.gif");
// Creating a Bitmap object from a file name
Bitmap curBitmap1 = new Bitmap("myfile.gif");
// Creating a Bitmap object from an Image object
Bitmap curBitmap2 = new Bitmap(curImage);
// Creating a Bitmap object with size and image
Bitmap curBitmap3 =
new Bitmap(curImage, new Size(200, 100) );
// Creating a Bitmap object with no images
Bitmap curBitmap4 = new Bitmap(200, 100);

Besides the constructor, the Bitmap class provides two static methods—FromHicon and FromResource—which can be used to create a Bitmap object from a window handle to an icon and from a Windows resource (.res file), respectively.

7.5.2 Viewing a Bitmap

Viewing a bitmap using the Bitmap class is similar to viewing an image. After constructing a Bitmap object, you just pass it as a parameter to DrawImage. The following code snippet creates a Bitmap object from a file and views the bitmap by calling the DrawImage method of a Graphics object associated with a form. You can write this code on a menu or a button click event handler.

Graphics g = this.CreateGraphics();
Bitmap bitmap = new Bitmap("myfile.jpg");
g.DrawImage(bitmap, 20, 20);
g.Dispose();

printDocument 사용하여 프린트할때요. 프린트대화상자가 나타나지 않게 하려면 어떻게 하죠?

PrintDocument 클래스에 보시면...

PrintController 속성이 있네요...

이 속성을 false로 해주시면 될 것 같습니다...

...

    ms-help://MS.VSCC/MS.MSDNVS.1042/cpref/html/frlrfSystemDrawingPrintingPrintDocumentMembersTopic.htm

...

그럼!~~~

윈도우 프로그래밍 시에 invalidate()

invalidate() 호출하면 그래픽 요소들이 사정없이 떨리면서 업데이트 되는 데 이걸 해결할 방법이 있나요?

이 글에 평점 주기:

2005-03-04 오후 4:12:52   /  번호: 47578  / 평점: (9.0)

Re: 더블 버퍼링


자게에 글올리셨던 분이군요.

더블 버퍼링을 하기 위해서는 폼의 Load이벤트에 아래의 코드를 넣습니다.

this.SetStyle(ControlStyles.DoubleBuffer,true);

this.SetStyle(ControlStyles.AllPaintingInWmPaint,true);

this.SetStyle(ControlStyles.UserPaint,true);

이 글에 평점 주기:

2005-03-04 오후 5:27:47   /  번호: 47587  / 평점: (-)

Re: 더블버퍼링의 사용에 대해서


답변 감사합니다. 막상 더블 버퍼링을 적용하려니 용법을 잘 모르겠습니다.

using  System;

using  System.Drawing;

using  System.Drawing.Drawing2D;

using  System.Windows.Forms;

class HowdyWorld:Form

{

    public static void Main()

    {

        Application.Run(new HowdyWorld());

    }

    public HowdyWorld()

    {

        Text="howdy, world";

        MinimumSize=SystemInformation.MinimumWindowSize+new Size(0,1);

    }

    public void EnableDoubleBuffering()

    {

       this.SetStyle(ControlStyles.DoubleBuffer |

          ControlStyles.UserPaint |

          ControlStyles.AllPaintingInWmPaint,

          true);

       this.UpdateStyles();

    }

    protected override void OnResize(EventArgs e)

    {

        Invalidate();

    }

    protected override void OnPaint(PaintEventArgs pea)

    {

        Graphics grfx=CreateGraphics();

        Color clr=ForeColor;

        float cx=ClientSize.Width;

        float cy=ClientSize.Height;

        Font font = new Font("Times New Roman", 10, FontStyle.Italic);

        SizeF sizef=grfx.MeasureString(Text, font);

        float fScale=Math.Min(cx/sizef.Width, cy/sizef.Height);

        Console.WriteLine(font.SizeInPoints);

        font=new Font(font.Name, fScale*font.SizeInPoints, font.Style);

        sizef=grfx.MeasureString(Text, font);

        grfx.DrawString(Text, font, new SolidBrush(clr), (cx-sizef.Width)/2, (cy-sizef.Height)/2);

    }

}

위와 같은 프로그램인데 어디에 더블 버퍼링을 추가해야 하나요?

이 글에 평점 주기:

2005-03-04 오후 6:35:30   /  번호: 47593  / 평점: (9.0)

Re: 그것은...


C#은 내부적으로 더블버퍼링을 해주기때문에

말씀드린대로 폼의 Load이벤트(혹은 생성자)에 코드를 넣어두기만 하면 됩니다.

OnPaint를 오버라이드하셨는데 그러면 더블버퍼링이 안되는걸로 알고있습니다.  <-난 계속이렇게 해서 삽실했따;;;

특별한 경우가 아니라면 Paint이벤트에서 그리는 작업을 하시면 더블버퍼링이 적용됩니다.

이 글에 평점 주기:

2005-03-04 오후 8:55:57   /  번호: 47600  / 평점: (9.0)

Re: 더블 버퍼링은...

Dc 영역을 제어해야합니다.

기본적으로 C#에서는 SetStyle 조건에 의해서 내부적으로 더블버퍼링을 제공하지만,

막상 사용하시다보면, 실제로 적용이 되는 부분은 님이 어떻게 코딩하는냐에 달렸습니다.

기본은 화면에 보여지는 Dc영역을 제어하여 그림을 뿌리거나, 글자를 넣거나, 하지만, 제어가 커지거나, 큰이미지를 넣어서 이동 같은

부분들을 넣다보면, 껌벅이는 부분이 보일겁니다.( 컴퓨터 사용이 좋다면, 작은 이미지는 느끼지 못하죠)

그래서 구현해야하는 것이 내부적으로 제어되는 dc 영역입니다.

화면은 항상 마지막 구현부분을 보여주며, 이 전의 작업은 내부적으로 작업하여 감추어 두는 거죠..

혹은 배경과 아이콘 영역을 따로 사용하는 것도 있으며, 아이콘의 영역의 사이즈를 주어 dc을 작게 제어하는 방법도 있습니다.

강좌는 많지 않은걸로 기억하며, 자료실의 그림판, 또는 이미지 로 검색하여, 소스를 보시는게 가장 쉽게 이해하실겁니다.

보시면 대부분이 dc 영역은 2가지로 표현되어 있지요..

전 C#으로 그림판하나 만들면서 충격을 많이 받았죠.. 아직도 모든 기능은 구현 못 했습니다.

VC++로 예전에 만든 것은 속도가 괜찮았으나, 다른 고수님들의 소스를 보면서 만들었기에..  나도 모르는 사이에 더블 버퍼링이 구현되었는지도

모릅니다.

c#을 하면 조금씩 알게된 Graphics의 Dc 영역은 놀라웠으며, 공부해야하는 범위가 넓었습니다.

C# 소스를 보시면서 주의해야할점은 OOP 개념이 많이 도입되어서 잘 만들어진 소스는 보면 볼 수록 이해가 안될겁니다.

잘 만들었다고 무조건 참고하시면 -_-ㅋ  머리 아포~^^;;

그럼 ㅅㄱ하세요

 

Re: DC가 먼가요?

그렇다면 더블버퍼링의 문제는 아닌 것 같군요.

저는 OnPaint에서 로직을 구현했거든요.

그렇다면 Dc라는 것을 파야  할 텐데.

Dc가 먼지에 대해 간단한 설명이도 부탁드립니다.

아니면 참고자료라도

 

Re: Device Context의 약자

깊이 공부하시려면 WinAPI 에 관련된 책을 하나 사서 보는게 빠를겁니다.

인터넷에서 체계적으로 개념을 정리하기는 쉽지 않죠.

클래스, 메소드 의 용법이나 활용등은 찾기 쉬워도요~

참고로 WinAPI 는 Window UI 를 C 로 짤 수 있도록 만들어진 API 입니다.

쓰기 불편하고 복잡하고 정신없기 때문에 거기에 골격을 붙여서 MFC 란게 나온거고요(이건 기본 문법이 C++ 입니다. C++ 이나 C 나 큰 차이는 없지만요)

꽤 편해지긴 했지만 여전히 새로 배우기에는 골차아프고 복잡하죠

C# 같은 경우는 UI 쪽으로 복잡한것들을 다 생략하고 엄청나게 간결하게 된겁니다. ^^

제가 보고 있는 Professional C# 책의 GDI 부분에 보니까 어느정도 설명이 나와있네요. (아 책 광고 하는건 아닙니다. 저도 학생이니까..)

Bitmap objBitmap = new Bitmap(Server.MapPath("images/empty.jpg")); //이건 빈 투명 이미지 입니다.
Graphics objGraphics = Graphics.FromImage(objBitmap);
Bitmap objBitmap2 = new Bitmap(Server.MapPath("images/hot.gif")); //이건 합치려는 이미지
Rectangle rect = new Rectangle(15,19,12,12); //이건 사이즈구여
objGraphics.DrawImageUnscaled(objBitmap2,rect);
objGraphics.Save();
objBitmap.Save(Server.MapPath("images/sam.gif"),ImageFormat.Gif); //만들어지는 이미지 입니다.
objBitmap2.Dispose();
objBitmap.Dispose();

 

 

//-----------------------------------------------------------------------
// This file is part of the Microsoft .NET SDK Code Samples.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
//This source code is intended only as a supplement to Microsoft
//Development Tools and/or on-line documentation. See these other
//materials for detailed information regarding Microsoft code samples.
//
//THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
//KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//PARTICULAR PURPOSE.
//-----------------------------------------------------------------------
namespace Microsoft.Samples.WinForms.Cs.PrintingExample5 {
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
public class PrintForm : System.Windows.Forms.Form {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components;
protected internal System.Windows.Forms.Button printButton;
protected internal System.Windows.Forms.Button pageSetupButton;
protected internal System.Windows.Forms.Button printPreviewButton;
private PageSettings storedPageSettings = null ;
public PrintForm() {
//
// Required for Windows Form Designer support
//
InitializeComponent();
// Wire up event handlers for print buttons
printButton.Click += new System.EventHandler(printButton_Click);
pageSetupButton.Click += new System.EventHandler(pageSetupButton_Click);
printPreviewButton.Click += new System.EventHandler(printPreviewButton_Click);
}
//Event fired when the user presses the page setup button
private void pageSetupButton_Click(object sender, EventArgs e) {
try {
PageSetupDialog psDlg = new PageSetupDialog() ;
if (storedPageSettings == null) {
storedPageSettings = new PageSettings();
}
psDlg.PageSettings = storedPageSettings ;
psDlg.ShowDialog();
} catch(Exception ex) {
MessageBox.Show("An error occurred - " + ex.Message);
}
}
//Event fired when the user presses the print button
private void printButton_Click(object sender, EventArgs e) {
try {
StreamReader streamToPrint = new StreamReader ("PrintMe.Txt");
try {
TextFilePrintDocument pd = new TextFilePrintDocument(streamToPrint); //Assumes the default printer
if (storedPageSettings != null) {
pd.DefaultPageSettings = storedPageSettings ;
}
PrintDialog dlg = new PrintDialog() ;
dlg.Document = pd;
DialogResult result = dlg.ShowDialog();
if (result == DialogResult.OK) {
pd.Print();
}
} finally {
streamToPrint.Close() ;
}
} catch(Exception ex) {
MessageBox.Show("An error occurred printing the file - " + ex.Message);
}
}
//Event fired when the user presses the print preview button
private void printPreviewButton_Click(object sender, EventArgs e) {
try {
StreamReader streamToPrint = new StreamReader ("PrintMe.Txt");
try {
TextFilePrintDocument pd = new TextFilePrintDocument(streamToPrint); //Assumes the default printer
if (storedPageSettings != null) {
pd.DefaultPageSettings = storedPageSettings ;
}
PrintPreviewDialog dlg = new PrintPreviewDialog() ;
dlg.Document = pd;
dlg.ShowDialog();
} finally {
streamToPrint.Close() ;
}
} catch(Exception ex) {
MessageBox.Show("An error occurred attempting to preview the file to print - " + ex.Message);
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing) {
if (components != null) {
components.Dispose();
}
}
base.Dispose(disposing);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container ();
this.printPreviewButton = new System.Windows.Forms.Button ();
this.pageSetupButton = new System.Windows.Forms.Button ();
this.printButton = new System.Windows.Forms.Button ();
this.Text = "Print Example 5";
this.AutoScaleBaseSize = new System.Drawing.Size (5, 13);
this.ClientSize = new System.Drawing.Size (504, 381);
printPreviewButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
printPreviewButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
printPreviewButton.Size = new System.Drawing.Size (136, 40);
printPreviewButton.TabIndex = 0;
printPreviewButton.Location = new System.Drawing.Point (32, 210);
printPreviewButton.Text = "Print Preview";
pageSetupButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
pageSetupButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
pageSetupButton.Size = new System.Drawing.Size (136, 40);
pageSetupButton.TabIndex = 0;
pageSetupButton.Location = new System.Drawing.Point (32, 160);
pageSetupButton.Text = "Page Settings";
printButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
printButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
printButton.Size = new System.Drawing.Size (136, 40);
printButton.TabIndex = 0;
printButton.Location = new System.Drawing.Point (32, 112);
printButton.Text = "Print the file";
this.Controls.Add (this.printButton);
this.Controls.Add (this.pageSetupButton);
this.Controls.Add (this.printPreviewButton);
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
public static void Main(string[] args) {
Application.Run(new PrintForm());
}
}
}

두번째 예제

-----------------------------------------------------------------------------------
StringReader streamToPrint = new StringReader (textArea.Text);
TextPrintDocument pd = new TextPrintDocument(streamToPrint,textArea.Font);
// 기본 프린터로 설정
if (storedPageSettings != null) {
pd.DefaultPageSettings = storedPageSettings ;
}
PrintDialog dlg = new PrintDialog() ;
dlg.Document = pd;
DialogResult result = dlg.ShowDialog();
if (result == DialogResult.OK) {
pd.Print();
}
--------------------------------------------------------------------------------------

private void Form1_Load(object sender,
  System.EventArgs e)
{
  // See if any printers are installed
  if( PrinterSettings.InstalledPrinters.Count <= 0)
  {
    MessageBox.Show("Printer not found!");
    return;
  }

  // Get all available printers and add them to the
  // combo box
  foreach(String printer in
    PrinterSettings.InstalledPrinters)
  {
    printersList.Items.Add(printer.ToString());
  }

}

System.Drawing.Bitmap bt; //비트맵 하나 만들어준다

  private void button1_Click(object sender, System.EventArgs e)
  {
   bt = new Bitmap(200,200);

   System.Drawing.Graphics curGraphics = Graphics.FromImage(bt);

//위에처럼 하면 비트맵에다가 그림을 그릴수 있따
   Pen pn = new Pen(Color.Red, 3);  
   curGraphics.DrawRectangle(pn, 50, 50, 100, 100);

  }

//printDocument1 실행되는 부분

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
  {
   e.Graphics.DrawImage(bt, 10,10,200,200);

}

+ Recent posts