#In Form Draw & In WndProc Event
#In Form Draw & In WndProc Event
#In Form Draw & In WndProc Event

using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace ConsoleForm
{
    public class ____ConsoleDraw : Form
    {
        private const int WM_KEYDOWN = 0x0100;
        private const int WM_PAINT = 0x000F;

        static int toggle=0;
        static int index=0;

        public ____ConsoleDraw()
        {
            //
        }
        protected override void WndProc(ref Message m) //해당 overrride 메소드에서 그래픽관련 핸들을 얻어야 합니다.
        {
            base.WndProc(ref m); 

            index++;
            Console.Write("Window Message Event:" + index.ToString("000000") + "/" + m.Msg + "/");
            Console.WriteLine("0x"+Convert.ToString(m.Msg, 16) + "/");

            switch(m.Msg)
            {
                case WM_PAINT:
                if(toggle==0)
                {
                    this.Size = new Size(800,600);
                    this.Text = "HatchStyle Window Information";
                    toggle=100;
                }
                break;
                case WM_KEYDOWN : 
                    Console.WriteLine("WM_KEYDOWN"); 

                    if (m.Msg == WM_KEYDOWN)
                    {
                        Keys keyCode = (Keys)m.WParam & Keys.KeyCode;

                        switch (keyCode)
                        {
                        case Keys.F1:
                        case Keys.F2:

                        MessageBox.Show("Control.PreProcessMessage: '" +
                          keyCode.ToString() + "' pressed.");
                        break;
                        }

                        if(Keys.F1 == keyCode)
                        {
                            Application.Exit();
                        }
                        if(Keys.F2 == keyCode)
                        {
                            Console.WriteLine("F2 Key Pressed!!");

                            Graphics graphics = CreateGraphics();
                            Pen pen = new Pen(Color.Black);
                            graphics.DrawLine(pen,10,10,50,10);
                            graphics.DrawLine(pen,50,10,50,50);

                            graphics.Dispose(); // Graphics에서 사용하는 리소스를 모두 해제합니다.
                        }
                        if(Keys.F3 == keyCode)
                        {
                            Graphics graphics = CreateGraphics();
                            Font font = new Font("고딕", 12, FontStyle.Bold);

                            //1.
                            for (int h = 0; h <= 52; h++)
                            {
                                HatchStyle hs = (HatchStyle)h;
                                Brush hb = new HatchBrush(hs, Color.White);
                                graphics.FillRectangle(hb, new Rectangle((h/26)*250, (h%26)*20, 50, 20));
                                graphics.DrawString(hs.ToString(), font, Brushes.DarkGreen, (h/26)*250+50, (h%26)*20);
                            }
 
                            //2.
                            Brush brush = new SolidBrush(Color.Green);
                            graphics.FillRectangle(brush, new Rectangle(500, 20, 50, 20));
                            graphics.DrawString("SolidBrush - Green", font, Brushes.Green, 550, 20);
 
                            //3.
                            Brush tb = new TextureBrush(image);
                            graphics.FillRectangle(tb, new Rectangle(500, 40, 50, 20));
                            graphics.DrawString("TextureBrush - myimage", font, Brushes.Green, 550, 40);
                        }
                    }
                    break;
                }
            }

            [STAThread]
            static void Main(string[] args)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new ____ConsoleDraw());
            }
      }//end of class
}//end of namespace 

 

#form hexa created by console(WndProc)
#form hexa created by console(WndProc)

#IDE 필요없음, Windows10 csc로 개발가능(메모장으로 개발)
#IDE 필요없음, Windows10 csc로 개발가능(메모장으로 개발)
#IDE 필요없음, Windows10 csc로 개발가능(메모장으로 개발)


Caution)Semaphor Needed, Duplicate DrawHexa Execution Error!!!!
Caution)Semaphor Needed, Duplicate DrawHexa Execution Error!!!!
Caution)Semaphor Needed, Duplicate DrawHexa Execution Error!!!!

DrawStyle 1)
DrawStyle 2)


#기본 sample(base sample code)

namespace WindowForm
{
public class ____KingDom : Form
{
private const int WM_KEYDOWN = 0x0100;
private const int WM_PAINT = 0x000F;
static int toggle=0;

static System.Timers.Timer timer;

static Graphics graphics;
static Font font;

public ____KingDom()
{
//
}
// 윈도우 메시지 처리 함수
protected override void WndProc(ref Message m)
{
  base.WndProc(ref m);
  // 메시지 콘솔 출력
  Console.Write(m.Msg + "/");
  Console.Write("0x"+Convert.ToString(m.Msg, 16) + "/");

  switch(m.Msg)
  {
    case WM_PAINT:
    if(toggle==0)
    {
      this.Size = new Size(800,800);
      this.Text = "HEXA BY CONSOLE FORM";

      graphics = CreateGraphics();
      font = new Font("바탕체", 17, FontStyle.Bold);

      toggle=100;

      timer = new System.Timers.Timer();
      timer.Interval = 1000;
      timer.Elapsed += new ElapsedEventHandler(__time_tick);
      timer.Start();

      MessageBox.Show("HEXA START, Time Interval:" + timer.Interval);

      init(ref hexa, ref xpos, ref ypos, ref __design);
      DrawHexa(hexa);
    }
    break;
    case 0x0100 :
    Console.WriteLine("WM_KEYDOWN");

    if (m.Msg == WM_KEYDOWN)
    {
      int ____keyCode=m.WParam.ToInt32();
      if(____keyCode == VK_RIGHT) //RIGHT
      {
        kk = f_rightkey(ref hexa, ref xpos, ref ypos, ref __design);
      }
      if(____keyCode == VK_LEFT) //LEFT
      {
        kk = f_leftkey(ref hexa, ref xpos, ref ypos, ref __design);
      }
      if(____keyCode == VK_SPACE) //SPACE
      {
        kk = f_spacekey(ref hexa, ref xpos, ref ypos, ref __design);
      }
      }
      break;
      }
    }

    [STAThread]
    static void Main(string[] args)
    {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new ____KingDom());
    }
  }
}

f13.cs
0.03MB

#SendMessage by User Forced & When F1 KeyDown, Process example
#SendMessage by User Forced & When F1 KeyDown, Process example
#SendMessage by User Forced & When F1 KeyDown, Process example


KEY_DOWN시에, 강제로 Message를 Send 한다.
WM_KEYDOWN시에, F1이 눌리면 F1이 눌렸다고 표시한다.

private const int WM_KEYDOWN        = 0x0100;

protected override void WndProc(ref Message m)
{
  base.WndProc(ref m);

  Console.WriteLine(m.Msg); //10진수로 표시
  Console.WriteLine("0x"+Convert.ToString(m.Msg, 16)); //16진수로 표시

  switch(m.Msg)
  {
    case 0x0203 : 
      Console.WriteLine("WM_LBUTTONDBLCLK      "); 
      Console.WriteLine("QUIT--------------------------------"); 
      Application.Exit(); //강제종료
      break;
    case 0x0100 : 
    Console.WriteLine("WM_KEYDOWN ####           ---------------"); 
    ____KingDom.SendMessage(this.Handle, WM_COPYDATA, 1, 2);

    if (m.Msg == WM_KEYDOWN)
    {
      Keys keyCode = (Keys)m.WParam & Keys.KeyCode;

      if(Keys.F1 == keyCode)
      {
        Console.WriteLine("F1 Key Pressed!!");
      }
    }
    break;
  }
}

 

send_msg.cs
0.03MB

#WndProc & Message(WM_MOVE) 예제




        // 윈도우 메시지 처리 함수
        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            // 메시지 콘솔 출력
            Console.WriteLine(m.Msg);
            Console.WriteLine("----------------------0x"+Convert.ToString(m.Msg, 16));
            switch(m.Msg)
            {
                case WM_MOVE : 
                    Console.WriteLine("WM_MOVE Message Occured!!");
                    break;
            }
        }

 

message_sh.cs
0.03MB

using System;
using System.Net;
using System.IO;

namespace NetKingdom
{
    class Program    
    {
        static WebRequest request;
        static WebResponse response;
        static Stream dataStream;
        static StreamReader reader;

        static void Main(string[] args)
        {
            request = WebRequest.Create("https://news.naver.com");//URL ADDRESS
            request.Method = "GET";
                
            response = request.GetResponse();
            dataStream = response.GetResponseStream();
            reader = new StreamReader(dataStream);
 
            string responseFromServer = reader.ReadToEnd();
 
            Console.WriteLine(responseFromServer); // response 출력
 
            reader.Close();
            dataStream.Close();
            response.Close();
        }
    }
}

#메시지 처리 함수 (WndProc)
메시지 처리 함수(WndProc) 란 WinMain에 메시지 루프에서 전달된 메시지를 처리해주는 함수입니다. 
이 WndProc 함수는 WinMain에서 호출하는것이 아닌 운영체제에서 호출합니다. 
이렇게 운영체제에서 호출하는 함수를 콜백 함수라고 합니다.
WinMain 내에 메시지 루프는 메시지를 전달하는 역활만 하고 
메시지 처리는 모두 이 WndProc 함수에서 처리가 됩니다.

DOS에서는 main 함수만 있으면 프로그램을 작성할 수 있지만
WINAPI에서는 특별한 경우를 제외하고는 메인 함수와 메시지 처리 함수 이 두 함수가 있어야 한다.

protected override void WndProc(ref Message m)
{
    base.WndProc(ref m);
    switch(m.Msg)
    {
        case APMApiPublic.UWM_CHANGE_HANDLE:,,,,,,,
        case APMApiPublic.WM_COPYDATA:,,,,,,
    }
}

이렇게 전달된 메시지를 프록시함수는 스위치 문으로 처리합니다.
WM_PAINT , WM_KEYDOWN 등등 전달된 메시지의 종류에 따라 다르게 처리를 합니다.
프로그램 종료 버튼을 누르면 WM_DESTROY 메시지가 실행이 되고
PostQuitMessage(0) 함수가 호출되는데 이 함수는 WM_QUIT 메시지를 생성시켜
프로그램을 종료하게됩니다.

스위치 문을 통과한 뒤 DefWindowProc() 함수를 리턴하게 되는데
이 함수는 메뉴 최소화, 최대화 ,윈도우 이동, 등을 프로그래머가 집적 손대지 않아도
운영체제가 알아서 처리해주는 함수입니다.

비고) Window c를 이용하는 프로그램에서 자주 다루어 졌던 내용입니다.

#region을 사용하면 #endregion으로 지시문을 종료해야 합니다. Visual Studio에서 #region에서 바로 다음으로 나오는 #endregion까지의 코드를 확대, 축소하며 작업을 할 수 있습니다. 

 

아래의 그림 1이 위 설명을 코드로 나타낸 것 입니다. 

[그림 1]

 

[그림 2]



비고)
#region을 쓰면 안될 때..
짜임새 있게 짜여지지 못한 코드의 경우 region으로 더 복잡해 질 수 있습니다.

 

 

/*------------------------------------------------------------------------
 double value;

 value = 123;
 Console.WriteLine(value.ToString("00000"));
 Console.WriteLine(String.Format("{0:00000}", value));
 // Displays 00123

 value = 1.2;
 Console.WriteLine(value.ToString("0.00", CultureInfo.InvariantCulture));
 Console.WriteLine(String.Format(CultureInfo.InvariantCulture,
                   "{0:0.00}", value));
 // Displays 1.20

 Console.WriteLine(value.ToString("00.00", CultureInfo.InvariantCulture));
 Console.WriteLine(String.Format(CultureInfo.InvariantCulture,
                                 "{0:00.00}", value));
 // Displays 01.20

 CultureInfo daDK = CultureInfo.CreateSpecificCulture("da-DK");
 Console.WriteLine(value.ToString("00.00", daDK));
 Console.WriteLine(String.Format(daDK, "{0:00.00}", value));
 // Displays 01,20

 value = .56;
 Console.WriteLine(value.ToString("0.0", CultureInfo.InvariantCulture));
 Console.WriteLine(String.Format(CultureInfo.InvariantCulture,
                                 "{0:0.0}", value));
 // Displays 0.6

 value = 1234567890;
 Console.WriteLine(value.ToString("0,0", CultureInfo.InvariantCulture));
 Console.WriteLine(String.Format(CultureInfo.InvariantCulture,
                                 "{0:0,0}", value));
 // Displays 1,234,567,890

 CultureInfo elGR = CultureInfo.CreateSpecificCulture("el-GR");
 Console.WriteLine(value.ToString("0,0", elGR));
Console.WriteLine(String.Format(elGR, "{0:0,0}", value));
 // Displays 1.234.567.890

 value = 1234567890.123456;
 Console.WriteLine(value.ToString("0,0.0", CultureInfo.InvariantCulture));
 Console.WriteLine(String.Format(CultureInfo.InvariantCulture,
                                 "{0:0,0.0}", value));
 // Displays 1,234,567,890.1

 value = 1234.567890;
 Console.WriteLine(value.ToString("0,0.00", CultureInfo.InvariantCulture));
 Console.WriteLine(String.Format(CultureInfo.InvariantCulture,
                                 "{0:0,0.00}", value));
 // Displays 1,234.57

------------------------------------------------------------------------*/
usnig System;
usnig System.IO;
usnig System.Timers;
usnig Kingdom;

namespace Kingdom
{
  class Program
  {
    static void Main(string[] args)
    {
      Episode pro=new Episode();
      pro.running();
    }
  }

  class Episode
  {
    DateTime now;
    ConsoleKey key;
    ConsoleKeyInfo keyinfo;
    Timer timer;
    int xpos,ypos;

    public void elapsed_time_func(object sender, ElapsedEventArgs e)
    {
      ypos++;
      Logging("Time");
    }

    public void running()
    {
      timer=new Timer();
      timer.Interval=1000;
      timer.Elapsed += new ElapsedEventHandler(elapsed_time_func);
      timer.Start();

      Logging("Start");

      while(true)
      {
        key=Console.ReadKey(true).Key;
        //keyinfo=Console.ReadKey(true);

        if(key==ConsoleKey.RightArrow) xpos++;
        else if(key==ConsoleKey.LeftArrow) xpos--;
        else if(key==ConsoleKey.DownArrow) ypos--;
        else if(key==ConsoleKey.Escape) break;

        /*if(keyinfo.KeyChar=='+')
        {
          timer.Stop();
          timer.Interval += 10;
          timer.Start();
        }
        else if(keyinfo.Key==ConsoleKey.RightArrow) xpos++*/
        Logging("Key");
      }
      timer.Stop();
      Logging("Stop");
   }

   public void Logging(string msg)
   {
      now=DateTime.Now;
      Console.WriteLine("Debug>>" + "Pos[" + ypos.ToString("0000") + "," + xpos.ToString("0000") + "]   Time:" + now.ToString("yyyy-MM-dd hh:mm:ss") + "    Event:" + msg);
   }
  }
}

+ Recent posts