반응형

* C# 움직이는 라벨 만들기 예제...

 

Main

 

-사용한 컨트롤 : Label 1 개, Panel 1개, Timer 1개

 

전체 소스 코드

Form1.cs

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CSharp_MoveLabel
{
    public partial class Form1 : Form
    {
        int iLocationX = 1;
        int iLocationY = 0;
        bool bCheck = true;      //true 앞으로 false 뒤로

        int iSpeed = 5;
        int iOffset = 10;

        public Form1()
        {
            InitializeComponent();

            iLocationY = (panel1.Height - panel1.Location.Y) / 2;
            Point p = new Point(iLocationX, iLocationY);
            label1.Location = p;

        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            timer1.Start();

        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);

            timer1.Stop();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //앞으로
            if (bCheck)
            {
                int iMove = iLocationX + label1.Width + iOffset ;
                int iEnd = panel1.Width ;

                if (iMove <= iEnd)
                {
                    iLocationX += iSpeed;
                    Point p = new Point(iLocationX, iLocationY);
                    label1.Location = p;
                }
                //끝지점에 도달 했으면...
                else
                {
                    bCheck = false;
                }

            }
            //뒤로
            else
            {
                //처음으로 다시 왔으면...
                if (iLocationX <= panel1.Location.X )
                {
                    bCheck = true;
                }
                else
                {
                    iLocationX -= iSpeed;
                    Point p = new Point(iLocationX, iLocationY);
                    label1.Location = p;
                }
            }
           
        }
    }
}

 

 

*예제 결과

 

 

반응형

+ Recent posts