首页 > 解决方案 > c#程序“随机”停止响应

问题描述

我正在尝试制作一个程序,在“不要踩到白块”游戏中寻找黑色瓷砖并将鼠标移动到那里。这一切都有效。(我知道我的代码和方法不是最好的)

但是在程序按预期工作几秒钟后,它停止响应(从任务管理器中看到)

这是代码:

public partial class Form1 : Form
    {
        [DllImport("user32.dll", EntryPoint = "SetCursorPos")]
        private static extern bool SetCursorPos(int X, int Y);

        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);
        //Mouse actions
        private const int MOUSEEVENTF_LEFTDOWN = 0x02;
        private const int MOUSEEVENTF_LEFTUP = 0x04;

        public void DoMouseClick()
        {
            //Call the imported function with the cursor's current position
            uint X = (uint)Cursor.Position.X;
            uint Y = (uint)Cursor.Position.Y;
            mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
        }

        public Form1()
        {
            InitializeComponent();

        }

        private async void Btn_start_ClickAsync(object sender, EventArgs e)
        {
            await Task.Delay(1500);

            Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            Graphics graphics = Graphics.FromImage(bitmap as Image);
            graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);

            int h = 850;
            int w;
            for (int i = 0; i < 999; i++)
            {
                w = 980;
                Color x = bitmap.GetPixel(w, h);
                do
                {
                    if (w > 1900) { w = 980; };
                    x = bitmap.GetPixel(w, h);
                    w += 3;
                } while (!(x.R == 0 && x.G == 0 && x.B == 0));

                await Task.Delay(50);
                Cursor.Position = new Point(w, h);
                //DoMouseClick();
                bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
                graphics = Graphics.FromImage(bitmap as Image);
                graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
                Debug.WriteLine(i);
            }
        }
    }
}

`

如果需要任何进一步的信息,请告诉我!我是一个试图学习的大菜鸟。

标签: c#winforms

解决方案


推荐阅读