Window creation: Difference between revisions

From Rosetta Code
Content added Content deleted
Line 119: Line 119:
return 0;
return 0;
}</lang>
}</lang>

{{libheader|GLUT}}

'''Compile command:''' gcc -I /usr/include/ -lglut -o window window_glut.c

Note that we aren't registering a painting or drawing callback, so the window will be created with nothing drawn in it. This is almost certain to lead to a strange appearance; On many systems, dragging the window around will appear to drag a copy of what was underneath where the window was when it was originally created.

We ''are'' registering a keypress callback, which isn't strictly necessary; It simply allows us to use a keypress to close the program rather than depending on the windowing system the program is run under.

<lang c>// A C+GLUT implementation of the Creating a Window task at Rosetta Code
// http://rosettacode.org/wiki/Creating_a_Window
#include <stdlib.h>
#include <GL/glut.h>

// This function is not strictly necessary to meet the requirements of the task.
void onKeyPress(unsigned char key, int x, int y)
{
// If you have any cleanup or such, you need to use C's
// onexit routine for registering cleanup callbacks.
exit(0);

}

int main(int argc, char **argv)
{
// Pulls out any command-line arguments that are specific to GLUT,
// And leaves a command-line argument set without any of those arguments
// when it returns.
// (If you want a copy, take a copy first.)
glutInit(&argc, argv);

// Tell GLUT we want to create a window.
// It won't *actually* be created until we call glutMainLoop below.
glutCreateWindow("Goodbye, World!");

// Register a callback to handle key press events (so we can quit on
// when someone hits a key) This part is not necessary to meet the
// requirements of the task.
glutKeyboardFunc(&onKeyPress);

// Put the execution of the app in glut's hands. Most GUI environments
// involve a message loop that communicate window events. GLUT handles
// most of these with defaults, except for any we register callbacks
// for. (Like the onKeyPress above.)
glutMainLoop();

return 0;

}

</lang>


=={{header|C++}}==
=={{header|C++}}==

Revision as of 02:36, 18 January 2010

Task
Window creation
You are encouraged to solve this task according to the task description, using any language you may know.

Ada

Library: GTK
Library: GtkAda

<lang ada>with Gtk.Window; use Gtk.Window; with Gtk.Widget; use Gtk.Widget;

with Gtk.Handlers; with Gtk.Main;

procedure Windowed_Application is

  Window : Gtk_Window;
  package Handlers is new Gtk.Handlers.Callback (Gtk_Widget_Record);
  package Return_Handlers is
     new Gtk.Handlers.Return_Callback (Gtk_Widget_Record, Boolean);
  function Delete_Event (Widget : access Gtk_Widget_Record'Class)
     return Boolean is
  begin
     return False;
  end Delete_Event;
  procedure Destroy (Widget : access Gtk_Widget_Record'Class) is
  begin
    Gtk.Main.Main_Quit;
  end Destroy;

begin

  Gtk.Main.Init;
  Gtk.Window.Gtk_New (Window);
  Return_Handlers.Connect
  (  Window,
     "delete_event",
     Return_Handlers.To_Marshaller (Delete_Event'Access)
  );
  Handlers.Connect
  (  Window,
     "destroy",
     Handlers.To_Marshaller (Destroy'Access)
  );
  Show (Window);
  Gtk.Main.Main;

end Windowed_Application;</lang>

AutoHotkey

<lang AutoHotkey>Gui, Add, Text,, Hello Gui, Show</lang>

C

Works with: ANSI C version C89
Library: SDL

Compile Command: gcc `sdl-config --cflags` `sdl-config --libs` SDL_Window.c -o window <lang c>/*

*   Opens an 800x600 16bit color window. 
*   Done here with ANSI C.
*/
  1. include <stdio.h>
  2. include <stdlib.h>
  3. include "SDL.h"

int main() {

 SDL_Surface *screen;
 
 if (SDL_Init(SDL_INIT_VIDEO) != 0) {
   fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError());
   return 1;
 }
 atexit(SDL_Quit);
 screen = SDL_SetVideoMode( 800, 600, 16, SDL_SWSURFACE | SDL_HWPALETTE );
 
 return 0;

}</lang>

Library: GTK

Compile command: gcc `gtk-config --cflags` `gtk-config --libs` -o window window.c

<lang c>#include <gtk/gtk.h>

int main(int argc, char *argv[]) {

 GtkWidget *window;
 gtk_init(&argc, &argv);
 window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
 gtk_signal_connect(GTK_OBJECT(window), "destroy",
   GTK_SIGNAL_FUNC(gtk_main_quit), NULL);
 gtk_widget_show(window);
 gtk_main();
 return 0;

}</lang>

Library: Gtk2

Compile command: gcc -Wall -pedantic `pkg-config --cflags gtk+-2.0` `pkg-config --libs gtk+-2.0` -o window window.c

<lang c>#include <gtk/gtk.h>

int main(int argc, char *argv[]) {

 GtkWidget *window;
 gtk_init(&argc, &argv);
 window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
 g_signal_connect (window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
 gtk_widget_show(window);
 gtk_main();
 return 0;

}</lang>

Library: GLUT

Compile command: gcc -I /usr/include/ -lglut -o window window_glut.c

Note that we aren't registering a painting or drawing callback, so the window will be created with nothing drawn in it. This is almost certain to lead to a strange appearance; On many systems, dragging the window around will appear to drag a copy of what was underneath where the window was when it was originally created.

We are registering a keypress callback, which isn't strictly necessary; It simply allows us to use a keypress to close the program rather than depending on the windowing system the program is run under.

<lang c>// A C+GLUT implementation of the Creating a Window task at Rosetta Code // http://rosettacode.org/wiki/Creating_a_Window

  1. include <stdlib.h>
  2. include <GL/glut.h>

// This function is not strictly necessary to meet the requirements of the task. void onKeyPress(unsigned char key, int x, int y) { // If you have any cleanup or such, you need to use C's // onexit routine for registering cleanup callbacks. exit(0);

}

int main(int argc, char **argv) { // Pulls out any command-line arguments that are specific to GLUT, // And leaves a command-line argument set without any of those arguments // when it returns. // (If you want a copy, take a copy first.) glutInit(&argc, argv);

// Tell GLUT we want to create a window. // It won't *actually* be created until we call glutMainLoop below. glutCreateWindow("Goodbye, World!");

// Register a callback to handle key press events (so we can quit on // when someone hits a key) This part is not necessary to meet the // requirements of the task. glutKeyboardFunc(&onKeyPress);

// Put the execution of the app in glut's hands. Most GUI environments // involve a message loop that communicate window events. GLUT handles // most of these with defaults, except for any we register callbacks // for. (Like the onKeyPress above.) glutMainLoop();

return 0;

}

</lang>

C++

Library: Qt

Compiler command: qmake -pro; qmake

<lang cpp>#include <QApplication>

  1. include <QMainWindow>

int main(int argc, char *argv[]) {

QApplication app(argc, argv);
QMainWindow window;
window.show();
return app.exec();

}</lang>

Library: GTK

Compiler command: g++ filename.cc -o test `pkg-config --cflags --libs gtkmm-2.4`

<lang cpp>#include <iostream>

  1. include <gtkmm.h>

int main( int argc, char* argv[] ) {

try
{
 Gtk::Main m( argc, argv ) ;
 Gtk::Window win ;
 m.run( win ) ;
}

catch( std::exception const & exc )
{
 std::cout << exc.what() << std::endl ;
 exit( -1 ) ;
}

exit( 0 ) ;

}</lang>

C#

Winforms

<lang csharp>using System; using System.Windows.Forms;

public class Window {

   [STAThread]
   static void Main() {
       Form form = new Form();
       
       form.Text = "Window";
       form.Disposed += delegate { Application.Exit(); };
       form.Show();
       Application.Run();
   }

}</lang>

Common Lisp

Library: CAPI

Works with: LispWorks

<lang lisp>(capi:display (make-instance 'capi:interface :title "A Window"))</lang>

Library: CLIM

Works with: McCLIM

Setting up the environment:

<lang lisp>(require :mcclim) (cl:defpackage #:rc-window

 (:use #:clim-lisp #:clim))

(cl:in-package #:rc-window)</lang>

The actual definition and display:

<lang lisp>(define-application-frame rc-window ()

 ()
 (:layouts (:default)))

(run-frame-top-level (make-application-frame 'rc-window))</lang>

Note: This creates a small, useless window ("frame"). Useful frames will have some panes defined inside them.

D

Library: FLTK4d

<lang d> module Window;

import fltk4d.all;

void main() {
    auto window = new Window(300, 300, "A window");
    window.show;
    FLTK.run;
}</lang>
Library: Derelict
Library: SDL

<lang d> import derelict.sdl.sdl;

int main(char[][] args)
{
    DerelictSDL.load();

    SDL_Event event;
    auto done = false;

    SDL_Init(SDL_INIT_VIDEO);
    scope(exit) SDL_Quit();

    SDL_SetVideoMode(1024, 768, 0, SDL_OPENGL);
    SDL_WM_SetCaption("My first Window", "SDL test");
	 
    while (!done)
    {
        if (SDL_PollEvent(&event) == 1)
        {
            switch (event.type)
	     {
                case SDL_QUIT:
	              done = true;
		          break;
		 default:
		      break;
	     }
	 }		
    }

   return 0;
}</lang>
Library: QD

QD is a simple and easy-to-use wrapper around SDL. <lang d> import qd;

void main() {
  screen(640, 480);
  while (true) events();
}</lang>

E

Swing

Works with: E-on-Java
when (currentVat.morphInto("awt")) -> {
    def w := <swing:makeJFrame>("Window")
    w.setContentPane(<swing:makeJLabel>("Contents"))
    w.pack()
    w.show()
}

Emacs Lisp

<lang lisp> (make-frame) </lang>

F#

Everything is provided by the .NET runtime so this is almost identical to C_sharp.

open System.Windows.Forms

[<System.STAThread>]
do
    Form(Text = "F# Window")
    |> Application.Run

Groovy

 import groovy.swing.SwingBuilder

 new SwingBuilder().frame(title:'My Window', size:[200,100]).show()

Haskell

Using

Library: HGL

from HackageDB.

A simple graphics library, designed to give the programmer access to most interesting parts of the Win32 Graphics Device Interface and X11 library without exposing the programmer to the pain and anguish usually associated with using these interfaces. <lang haskell>import Graphics.HGL

aWindow = runGraphics $

 withWindow_ "Rosetta Code task: Creating a window" (300, 200) $ \ w -> do

drawInWindow w $ text (100, 100) "Hello World" getKey w</lang>

IDL

With some example values filled in:

Id = WIDGET_BASE(TITLE='Window Title',xsize=200,ysize=100)
WIDGET_CONTROL, /REALIZE, id

J

A minimalist modal dialog: <lang j> title=: '"Hamlet -- Act 3, Scene 1"'

  text=: '"To be, or not to be: that is the question:"'
  wd 'mb ',title,text

</lang> A free-standing window: <lang j>MINWDW=: noun define pc minwdw; pas 162 85;pcenter; rem form end; )

minwdw_run=: monad define

 wd MINWDW
 wd 'pshow;'

)

minwdw_close=: monad define

 wd'pclose'

)

minwdw_run </lang>

Java

Library: Swing

<lang java>import javax.swing.JFrame;

public class Main {

    public static void main(String[] args) throws Exception {
        JFrame w = new JFrame("Title");
        w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        w.setSize(800,600);
        w.setVisible(true);
    }

}</lang>

JavaScript

   window.open("webpage.html", "windowname", "width=800,height=600");

mIRC Scripting Language

Works with: mIRC

Switches: C = Center Window p = Picture Window d = Desktop Window

alias CreateMyWindow {
 .window -Cp +d @WindowName 600 480
}

Objective-C

Works with: GNUstep
Works with: Cocoa

It opens a 800×600 window, centered on the screen, with title "A Window".

<lang objc>#include <Foundation/Foundation.h>

  1. include <AppKit/AppKit.h>

@interface Win : NSWindow { } - (void)applicationDidFinishLaunching: (NSNotification *)notification; - (BOOL)applicationShouldTerminateAfterLastWindowClosed: (NSNotification *)notification; @end


@implementation Win : NSWindow -(id) init {

 [self 
   initWithContentRect: NSMakeRect(0, 0, 800, 600)
   styleMask: (NSTitledWindowMask | NSClosableWindowMask)
   backing: NSBackingStoreBuffered
   defer: NO];
 [self setTitle: @"A Window"];
 [self center];
 return self;

}


-(void) dealloc {

 [super dealloc];

}

- (void)applicationDidFinishLaunching: (NSNotification *)notification {

 [self orderFront: self];

}

- (BOOL)applicationShouldTerminateAfterLastWindowClosed: (NSNotification *)notification {

 return YES;

} @end

int main() {

 Win *mywin;
 NSAutoreleasePool *pool;
 pool = [[NSAutoreleasePool alloc] init];
 [NSApplication sharedApplication];
 mywin = [[Win alloc] init];
 [NSApp setDelegate: mywin];
 [NSApp runModalForWindow: mywin];
 return EXIT_SUCCESS;

}</lang>

OCaml

  • with Labltk, the ocaml Tk binding (included with OCaml):

<lang ocaml>let () =

 let top = Tk.openTk() in
 Wm.title_set top "An Empty Window";
 Wm.geometry_set top "240x180";
 Tk.mainLoop ();
</lang>

execute with:

ocaml -I +labltk labltk.cma sample.ml

<lang ocaml>let () =

   Sdl.init [`VIDEO];
   let _ = Sdlvideo.set_video_mode 200 200 [] in
   Sdltimer.delay 2000;
   Sdl.quit ()</lang>

execute with:

ocaml bigarray.cma -I +sdl sdl.cma sample.ml

<lang ocaml>open Xlib

let () =

 let d = xOpenDisplay "" in
 let s = xDefaultScreen d in
 let w = xCreateSimpleWindow d (xRootWindow d s) 10 10 100 100 1
                               (xBlackPixel d s) (xWhitePixel d s) in
 xSelectInput d w [KeyPressMask];
 xMapWindow d w;
 let _ = xNextEventFun d in  (* waits any key-press event *)
 xCloseDisplay d;
</lang>

execute with:

ocaml -I +Xlib Xlib.cma sample.ml
  • with LablGTK2, the GTK2 OCaml binding:

<lang ocaml>open GMain

let window = GWindow.window ~border_width:2 () let button = GButton.button ~label:"Hello World" ~packing:window#add ()

let () =

 window#event#connect#delete  ~callback:(fun _ -> true);
 window#connect#destroy ~callback:Main.quit;
 button#connect#clicked ~callback:window#destroy;
 window#show ();
 Main.main ()</lang>

execute with:

ocaml -I +lablgtk2  lablgtk.cma gtkInit.cmo sample.ml

Oz

<lang oz>functor import

  Application
  QTk at 'x-oz://system/wp/QTk.ozf'

define

  proc {OnClose}
     {Application.exit 0}
  end
  %% Descripe the GUI in a declarative style.
  GUIDescription = td(label(text:"Hello World!")

action:OnClose %% Exit app when window closes. )

  %% Create a window object from the description and show it.
  Window = {QTk.build GUIDescription}
  {Window show}

end</lang>

Perl

Works with: Perl version 5.8.8
Library: Tk

<lang perl> use Tk;

 MainWindow->new();
 MainLoop;</lang>
Library: SDL

<lang perl> use SDL::App;

 use SDL::Event;
 
 $app = SDL::App->new;
 $app->loop({
   SDL_QUIT() => sub { exit 0; },
 });</lang>
Library: GTK

<lang perl> use Gtk '-init';

 $window = Gtk::Window->new;
 $window->signal_connect(
   'destroy' => sub { Gtk->main_quit; }
 );
 $window->show_all;
 Gtk->main;</lang>
Library: Gtk2

<lang perl> use Gtk2 '-init';

 $window = Gtk2::Window->new;
 $window->signal_connect(
   'destroy' => sub { Gtk2->main_quit; }
 );
 $window->show_all;
 Gtk2->main;</lang>
Library: XUL::GuiGui

<lang perl>use XUL::Gui;

display Window;</lang>

PowerShell

<lang powershell>[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null $form = New-Object Windows.Forms.Form $form.Text = "A Window" $form.Size = New-Object Drawing.Size(150,150) $form.ShowDialog() | Out-Null</lang>

Python

Works with: Python version 2.4 and 2.5
Library: Tkinter

<lang python> import Tkinter

 w = Tkinter.Tk()
 w.mainloop()</lang>
Library: wxPython

<lang python> from wxPython.wx import *

 class MyApp(wxApp):
   def OnInit(self):
     frame = wxFrame(NULL, -1, "Hello from wxPython")
     frame.Show(true)
     self.SetTopWindow(frame)
     return true
 
 app = MyApp(0)
 app.MainLoop()</lang>
Library: Pythonwin

<lang python> import win32ui

 from pywin.mfc.dialog import Dialog
 
 d = Dialog(win32ui.IDD_SIMPLE_INPUT)
 d.CreateWindow()</lang>
Library: PyGTK

<lang python> import gtk

 window = gtk.Window()
 window.show()
 gtk.main()</lang>

RapidQ

  create form as qform
     center
     width=500
     height=400
  end create
  form.showModal

Ruby

Works with: Ruby version 1.8.5
Library: Ruby/Tk

<lang ruby> require 'tk'

window = TkRoot::new()
window::mainloop()</lang>
Library: GTK

<lang ruby> require 'gtk2'

window = Gtk::Window.new.show
Gtk.main</lang>

Scala

Library: sdljava

<lang scala>import javax.swing.JFrame

object ShowWindow{

 def main(args: Array[String]){
   var jf = new JFrame("Hello!")
   jf.setSize(800, 600)
   jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
   jf.setVisible(true)
 }

}</lang>

Using native Scala libraries (which are wrappers over Java libraries):

<lang scala>import scala.swing._ import scala.swing.Swing._

object SimpleWindow extends SimpleSwingApplication {

 def top = new MainFrame {
   title = "Hello!"
   preferredSize = ((800, 600):Dimension)
 }

}</lang>

Tcl

Library: Tk

Loading the Tk package is all that is required to get an initial window: <lang tcl>package require Tk</lang> If you need an additional window: <lang tcl>toplevel .top</lang> If you are using the increasingly popular tclkit under MS Windows, all you have to do is associate the tclkit with the extension “.tcl” and then create an empty file with, e.g., with the name nothing.tcl. Double-clicking that will “open a window” (an empty one).

TI-89 BASIC

Dialog
  Title "Rosetta Code"
  Text ""
EndDlog

Toka

Library: SDL

Toka does not inherently know about graphical environments, but can interact with them using external libraries. This example makes use of the SDL library bindings included with Toka.

needs sdl
800 600 sdl_setup

Vedit macro language

Creates an empty window with ID 'A' near the upper left corner of document area, with height of 20 text lines and width of 80 characters. <lang vedit>Win_Create(A, 2, 5, 20, 80)</lang> Note: if you run this command while in Visual Mode, you should adjust your active window smaller so that the created window will not be hidden behind it (since the active window is always on top).

Visual Basic .NET

<lang vb> Dim newForm as new Form

   newForm.Text = "It's a new window"
  
       newForm.Show()</lang>