Setting position of a Console Window opened in a WinForms App

后端 未结 1 334
清酒与你
清酒与你 2020-12-13 20:41

I found some source code in this thread posted by Rex Logan here on SO :

link text

... there\'s also some very interesting code posted in this same threa

相关标签:
1条回答
  • 2020-12-13 21:31

    you can try something like this.

    This code set the position of the Console Window in a Console Application.

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Runtime.InteropServices;
    
    
    namespace ConsoleApplication10
    {
      class Program
      {
        const int SWP_NOSIZE = 0x0001;
    
    
        [DllImport("kernel32.dll", ExactSpelling = true)]
        private static extern IntPtr GetConsoleWindow();
    
        private static IntPtr MyConsole = GetConsoleWindow();
    
        [DllImport("user32.dll", EntryPoint = "SetWindowPos")]
        public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);
    
        static void Main(string[] args)
        {
          int xpos = 300;
          int ypos = 300;
          SetWindowPos(MyConsole, 0, xpos, ypos, 0, 0, SWP_NOSIZE);
          Console.WriteLine("any text");
          Console.Read();
        }
      }
    }
    

    This code set the position of the Console Window in a WinForm Application.

    using System;
    using System.Collections.Generic;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;
    
    
    namespace WindowsFormsApplication10
    {
      static class Program
      {
    
        const int SWP_NOSIZE = 0x0001;
    
        [System.Runtime.InteropServices.DllImport("kernel32.dll")]
        private static extern bool AllocConsole();
    
        [DllImport("user32.dll", EntryPoint = "SetWindowPos")]
        public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);
    
        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern IntPtr GetConsoleWindow();
    
        [STAThread]
        static void Main()
        {
          AllocConsole();
          IntPtr MyConsole = GetConsoleWindow();
          int xpos = 1024;
          int ypos = 0;
          SetWindowPos(MyConsole, 0, xpos, ypos, 0, 0, SWP_NOSIZE);
          Console.WindowLeft=0;
          Console.WriteLine("text in my console");
    
          Application.EnableVisualStyles();
          Application.SetCompatibleTextRenderingDefault(false);
          Application.Run(new Form1());
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题