Вы должны войти, чтобы создавать сообщения и темы.

Бот помощник по работе и играм.

Доброго времени суток Всем!

Пишу программу бот для дома, но С# изучаю недавно.. По жизни паскаль и ORA Sql.
Помогите написать программу чтобы она могла работать на не активных окнах...

Дома приходиться трудиться на нескольких работах - локалка и несколько виртуалок с VPN. Работаю дискретно 🙂 мотаясь по окнам, бот поможет как минимум поддерживать активность! Пароли стали длиннее, а время ожидания наоборот уменьшили.
Как максимум научить бота и распознавать кнопки нажимать осмыслено нужные команды...

Перепробовал разные кликеры: большинство не умеют в неактивном окне, а тот что умеет - имеет свой процедурный язык с жёсткими ограничениями.
Потому и решил своего бота создать, за одно понять и изучить новый современный язык!

Привет. Делал как-то кликер, делюсь кодом, надеюсь поможет)

Код

public partial class Form1 : Form {


    #region Windows

    [StructLayout(LayoutKind.Sequential)]
    struct RECT {

        public int left;
        public int top;
        public int right;
        public int bottom;
    }

    [DllImport("user32.dll", SetLastError = true)]
    static extern bool GetWindowRect(IntPtr hWnd, ref RECT Rect);

    [DllImport("user32.dll", SetLastError = true)]
    static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int Width, int Height, bool Repaint);

    [DllImport("user32.dll")]
    static extern int SendMessage(IntPtr hWnd, uint wMsg, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

    static IntPtr MAKEWPARAM(int direction, float multiplier, int button) =>
        (IntPtr)(((int)(SystemInformation.MouseWheelScrollDelta * multiplier) << 16) * Math.Sign(direction) | (ushort)button);

    enum vmMouse {

        lButton = 0x01,
        rButton = 0x02,

        LeftDown = 0x0201,
        LeftUp = 0x0202,
        RightDown = 0x0204,
        RightUp = 0x0205,

        mButton = 0x04,
        Wheel = 0x020A,

        Move = 0x0200,
        Hover = 0x02A1,
    }
    
    IntPtr CreatePos(int LoWord, int HiWord) => (IntPtr)((HiWord << 16) | (LoWord & 0xffff));
    

    #endregion

    #region set focus

    [DllImport("user32.dll")]
    static extern bool SetForegroundWindow(IntPtr hWnd);

    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    #endregion

    #region get color of pixel

    [DllImport("user32.dll")]
    static extern IntPtr GetDC(IntPtr hwnd);

    [DllImport("user32.dll")]
    static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc);

    [DllImport("gdi32.dll")]
    static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);

    static Color GetPixelColor(IntPtr handle, int x, int y) {

        IntPtr hdc = GetDC(handle);

        uint pixel = GetPixel(hdc, x, y);
        ReleaseDC(handle, hdc);

        return Color.FromArgb((int)(pixel & 0x000000FF),
                        (int)(pixel & 0x0000FF00) >> 8,
                        (int)(pixel & 0x00FF0000) >> 16);
    }


    #endregion
    
    // получить цвет пикселя приложения по x y, даже если оно неактивно \ закрыто другим окном
    Color getPixel(IntPtr handle, int x, int y) => print.PrintWindow(handle).GetPixel(x, y);

    // полное изображение приложения, даже если оно неактивно \ закрыто другим окном
    Bitmap getFullImage(IntPtr handle) => print.PrintWindow(handle);
    
    
    // если нужно получать x y курсора
    async void getCoords() {

        while (true) {

            label1.Text = MousePosition.ToString();
            await Task.Delay(100);
            GC.Collect();
        }
    }
    
    // вызов клика мыши сразу в приложение
    void leftClick(IntPtr handle, int x, int y) {
        SendMessage(handle, (uint)vmMouse.LeftDown, new IntPtr((int)vmMouse.lButton), CreatePos(x, y));
        SendMessage(handle, (uint)vmMouse.LeftUp, new IntPtr((int)vmMouse.lButton), CreatePos(x, y));
    }
    void rightClick(IntPtr handle, int x, int y) {
        SendMessage(handle, (uint)vmMouse.RightDown, new IntPtr((int)vmMouse.rButton), CreatePos(x, y));
        SendMessage(handle, (uint)vmMouse.RightUp, new IntPtr((int)vmMouse.rButton), CreatePos(x, y));
    }


    /*
    
    // получить handle процесса, например, дискорда
    foreach (Process p in Process.GetProcessesByName("discord")) {
    
    
        IntPtr handle = p.MainWindowHandle;
        
        // получение положения окна
        RECT rect = new RECT();
        GetWindowRect(handle, ref rect);
        
        // если нужно сделать окно активным
        // SetForegroundWindow(handle);
        
        // если нужно развернуть окно
        // ShowWindow(handle, 1);
        
        // передвинуть окно и\или поменять его размер
        // x, y, ширина, высота
        // MoveWindow(handle, 0, 0, 940, 600, true)
        
        
        // вызов ЛКМ
        leftClick(handle, 123, 456);
        
        // получить определенный пиксель
        Color pixel = getPixel(handle, 123, 456);
        
        
        // есть метод для вызова колесика мыши, но у Меня не получилось сделать так, чтобы он работал, 
        // если закрыть координаты x y другим окном
        // float f это множитель прокрутки 
        void wheel(int i, float f, int x, int y) => PostMessage(handle, (uint)vmMouse.Wheel, MAKEWPARAM(i, f, 0x0001), CreatePos(rect.left + x, rect.top + y));

        // вызов: -1 вниз | 1 вверх, множитель, x, y
        wheel(-1, .6f, 123, 456);
    }
    
    */
}

public static class print {

    [DllImport("user32.dll")]
    static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
    [DllImport("user32.dll")]
    static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, int nFlags);

    public static Bitmap PrintWindow(IntPtr hwnd) {

        GetWindowRect(hwnd, out RECT rc);

        Bitmap bmp = new Bitmap(rc.Width, rc.Height, PixelFormat.Format32bppArgb);
        Graphics gfxBmp = Graphics.FromImage(bmp);
        IntPtr hdcBitmap = gfxBmp.GetHdc();

        PrintWindow(hwnd, hdcBitmap, 2);

        gfxBmp.ReleaseHdc(hdcBitmap);
        gfxBmp.Dispose();

        return bmp;
    }


    [StructLayout(LayoutKind.Sequential)]
    public struct RECT {
        private int _Left;
        private int _Top;
        private int _Right;
        private int _Bottom;

        public RECT(RECT Rectangle) : this(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Bottom) {
        }
        public RECT(int Left, int Top, int Right, int Bottom) {
            _Left = Left;
            _Top = Top;
            _Right = Right;
            _Bottom = Bottom;
        }

        public int X {
            get { return _Left; }
            set { _Left = value; }
        }
        public int Y {
            get { return _Top; }
            set { _Top = value; }
        }
        public int Left {
            get { return _Left; }
            set { _Left = value; }
        }
        public int Top {
            get { return _Top; }
            set { _Top = value; }
        }
        public int Right {
            get { return _Right; }
            set { _Right = value; }
        }
        public int Bottom {
            get { return _Bottom; }
            set { _Bottom = value; }
        }
        public int Height {
            get { return _Bottom - _Top; }
            set { _Bottom = value + _Top; }
        }
        public int Width {
            get { return _Right - _Left; }
            set { _Right = value + _Left; }
        }
        public Point Location {
            get { return new Point(Left, Top); }
            set {
                _Left = value.X;
                _Top = value.Y;
            }
        }
        public Size Size {
            get { return new Size(Width, Height); }
            set {
                _Right = value.Width + _Left;
                _Bottom = value.Height + _Top;
            }
        }

        public static implicit operator Rectangle(RECT Rectangle) => new Rectangle(Rectangle.Left, Rectangle.Top, Rectangle.Width, Rectangle.Height);

        public static implicit operator RECT(Rectangle Rectangle) => new RECT(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Bottom);

        public static bool operator ==(RECT Rectangle1, RECT Rectangle2) => Rectangle1.Equals(Rectangle2);

        public static bool operator !=(RECT Rectangle1, RECT Rectangle2) => !Rectangle1.Equals(Rectangle2);


        public override string ToString() => "{Left: " + _Left + "; " + "Top: " + _Top + "; Right: " + _Right + "; Bottom: " + _Bottom + "}";


        public override int GetHashCode() => ToString().GetHashCode();


        public bool Equals(RECT Rectangle) => Rectangle.Left == _Left && Rectangle.Top == _Top && Rectangle.Right == _Right && Rectangle.Bottom == _Bottom;


        public override bool Equals(object Object) {

            if (Object is RECT rect)
                return Equals(rect);

            else if (Object is Rectangle rectangle)
                return Equals(new RECT(rectangle));

            return false;
        }
    }
}

Лайкнул XpucT
XpucT

Для простоты залил проект, чтобы не пришлось вставлять код: *тык*

Цитата: yuri от 08.09.2022, 23:39

Для простоты залил проект, чтобы не пришлось вставлять код: *тык*

Спасибо! Изучаю ... упрусь рогом напишу! 🙂

Лайкнули XpucT и yuri
XpucTyuri