본문 바로가기
코딩연습/C#

[C#]윈폼(Windows Form)에 마우스 이벤트로 폼 배경 변경(랜덤)

by 호아니 2020. 6. 16.

마우스 왼쪽 버튼을 누르면 윈도우 배경색을 랜덤으로 바꿔준다

마우스 오른쪽 버튼 누르면 사진배경을 띄워준다

마우스 휠을 움직이면 창이 투명해지게 만들어준다.

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
using System.Drawing;
using System.Diagnostics;

namespace ConsoleApp1
{
    class MainApp:Form
    {
        Random rand;
        public MainApp()
        {
            rand = new Random();
            this.MouseWheel += new MouseEventHandler(MainApp_Mouse2);
            this.MouseDown += new MouseEventHandler(MainApp_Mouse1);
        
        void MainApp_Mouse1(object sender,MouseEventArgs e)
        {
            //마우스 왼쪽 버튼 누르면 윈도우 배경을 랜덤 색상으로 만들기
            if (e.Button == MouseButtons.Left)
            {
                Color oldcolor = this.BackColor;
                this.BackColor = Color.FromArgb(rand.Next(0, 255),
                                                rand.Next(0, 255),
                                                rand.Next(0, 255));
            }
            //마우스 오른쪽 버튼 누르면 사진배경을 만들기
            else if(e.Button == MouseButtons.Right)
            {
                if(this.BackgroundImage != null)
                {
                    this.BackgroundImage = null;
                    return;
                }

                string file = "c:\\Temp\\sample.png";
                if (System.IO.File.Exists(file) == false) MessageBox.Show("이미지 파일이 없습니다");
                else this.BackgroundImage = Image.FromFile(file);
            }
        }
        void MainApp_Mouse2(object sender, MouseEventArgs e)
        {
                //마우스 휠을 움직이면 창이 투명해지게 만들기
                this.Opacity = this.Opacity + (e.Delta > 0 ? 0.1 : -0.1);
                Console.WriteLine($"오퍼시티:{this.Opacity}");

        }
}
        static void Main(string[] args)
        {
            Application.Run(new MainApp());

        }
    }
}