Windows 작업(C++/CLI)

Windows SDK를 사용하여 다양한 Windows 관련 작업을 보여 줍니다.

다음 항목에서는 Visual C++를 사용하여 Windows SDK로 수행되는 다양한 Windows 작업을 보여 줍니다.

종료가 시작되었는지 확인

다음 코드 예제에서는 애플리케이션 또는 .NET Framework가 현재 종료되는지 여부를 확인하는 방법을 보여 줍니다. 이는 종료하는 동안 시스템에서 이러한 구문을 완료하고 안정적으로 사용할 수 없기 때문에 .NET Framework의 정적 요소에 액세스하는 데 유용합니다. 속성을 먼저 검사 HasShutdownStarted 이러한 요소에 액세스하지 않으면 잠재적인 오류를 방지할 수 있습니다.

예시

// check_shutdown.cpp
// compile with: /clr
using namespace System;
int main()
{
   if (Environment::HasShutdownStarted)
      Console::WriteLine("Shutting down.");
   else
      Console::WriteLine("Not shutting down.");
   return 0;
}

사용자 대화형 상태 확인

다음 코드 예제에서는 코드가 사용자 대화형 컨텍스트에서 실행되고 있는지 여부를 확인하는 방법을 보여 줍니다. false이면 UserInteractive 코드가 서비스 프로세스로 실행되거나 웹 애플리케이션 내부에서 실행되므로 사용자와 상호 작용을 시도해서는 안 됩니다.

예시

// user_interactive.cpp
// compile with: /clr
using namespace System;

int main()
{
   if ( Environment::UserInteractive )
      Console::WriteLine("User interactive");
   else
      Console::WriteLine("Noninteractive");
   return 0;
}

Windows 레지스트리에서 데이터 읽기

다음 코드 예제에서는 키를 사용하여 CurrentUser Windows 레지스트리에서 데이터를 읽습니다. 먼저 하위 키는 메서드를 사용하여 GetSubKeyNames 열거된 다음, 메서드를 사용하여 OpenSubKey Identities 하위 키가 열립니다. 루트 키와 마찬가지로 각 하위 키는 클래스로 RegistryKey 표시됩니다. 마지막으로 새 RegistryKey 개체는 키/값 쌍을 열거하는 데 사용됩니다.

예시

// registry_read.cpp
// compile with: /clr
using namespace System;
using namespace Microsoft::Win32;

int main( )
{
   array<String^>^ key = Registry::CurrentUser->GetSubKeyNames( );

   Console::WriteLine("Subkeys within CurrentUser root key:");
   for (int i=0; i<key->Length; i++)
   {
      Console::WriteLine("   {0}", key[i]);
   }

   Console::WriteLine("Opening subkey 'Identities'...");
   RegistryKey^ rk = nullptr;
   rk = Registry::CurrentUser->OpenSubKey("Identities");
   if (rk==nullptr)
   {
      Console::WriteLine("Registry key not found - aborting");
      return -1;
   }

   Console::WriteLine("Key/value pairs within 'Identities' key:");
   array<String^>^ name = rk->GetValueNames( );
   for (int i=0; i<name->Length; i++)
   {
      String^ value = rk->GetValue(name[i])->ToString();
      Console::WriteLine("   {0} = {1}", name[i], value);
   }

   return 0;
}

설명

클래스는 Registry 정적 인스턴스 RegistryKey에 대한 컨테이너일 뿐입니다. 각 인스턴스는 루트 레지스트리 노드를 나타냅니다. 인스턴스는 ClassesRoot, CurrentConfig, CurrentUserLocalMachineUsers.

정적 개체 외에도 클래스 내의 Registry 개체는 읽기 전용입니다. 또한 레지스트리 개체의 내용에 RegistryKey 액세스하기 위해 만들어진 클래스의 인스턴스도 읽기 전용입니다. 이 동작을 재정의하는 방법의 예는 방법: Windows 레지스트리에 데이터 쓰기(C++/CLI)를 참조하세요.

클래스 DynData 에는 두 개의 추가 개체가 Registry 있습니다PerformanceData. 둘 다 클래스의 인스턴스입니다 RegistryKey . 이 개체에는 DynData Windows 98 및 Windows Me에서만 지원되는 동적 레지스트리 정보가 포함되어 있습니다. 이 개체를 PerformanceData 사용하여 Windows 성능 모니터ing System을 사용하는 애플리케이션의 성능 카운터 정보에 액세스할 수 있습니다. 노드는 PerformanceData 실제로 레지스트리에 저장되지 않아 Regedit.exe를 사용하여 볼 수 없는 정보를 나타냅니다.

Windows 성능 카운터 읽기

일부 애플리케이션 및 Windows 하위 시스템은 Windows 성능 시스템을 통해 성능 데이터를 노출합니다. 이러한 카운터는 네임스페이스에 상주하는 클래스 및 PerformanceCounter 클래스를 System.Diagnostics 사용하여 PerformanceCounterCategory 액세스할 수 있습니다.

다음 코드 예제에서는 이러한 클래스를 검색 하 고 프로세서가 사용 중인 시간의 비율을 나타내기 위해 Windows에서 업데이트 되는 카운터를 표시 합니다.

참고 항목

이 예제를 Windows Vista에서 실행하려면 관리 권한이 필요합니다.

예시

// processor_timer.cpp
// compile with: /clr
#using <system.dll>

using namespace System;
using namespace System::Threading;
using namespace System::Diagnostics;
using namespace System::Timers;

ref struct TimerObject
{
public:
   static String^ m_instanceName;
   static PerformanceCounter^ m_theCounter;

public:
   static void OnTimer(Object^ source, ElapsedEventArgs^ e)
   {
      try
      {
         Console::WriteLine("CPU time used: {0,6} ",
          m_theCounter->NextValue( ).ToString("f"));
      }
      catch(Exception^ e)
      {
         if (dynamic_cast<InvalidOperationException^>(e))
         {
            Console::WriteLine("Instance '{0}' does not exist",
                  m_instanceName);
            return;
         }
         else
         {
            Console::WriteLine("Unknown exception... ('q' to quit)");
            return;
         }
      }
   }
};

int main()
{
   String^ objectName = "Processor";
   String^ counterName = "% Processor Time";
   String^ instanceName = "_Total";

   try
   {
      if ( !PerformanceCounterCategory::Exists(objectName) )
      {
         Console::WriteLine("Object {0} does not exist", objectName);
         return -1;
      }
   }
   catch (UnauthorizedAccessException ^ex)
   {
      Console::WriteLine("You are not authorized to access this information.");
      Console::Write("If you are using Windows Vista, run the application with ");
      Console::WriteLine("administrative privileges.");
      Console::WriteLine(ex->Message);
      return -1;
   }

   if ( !PerformanceCounterCategory::CounterExists(
          counterName, objectName) )
   {
      Console::WriteLine("Counter {0} does not exist", counterName);
      return -1;
   }

   TimerObject::m_instanceName = instanceName;
   TimerObject::m_theCounter = gcnew PerformanceCounter(
          objectName, counterName, instanceName);

   System::Timers::Timer^ aTimer = gcnew System::Timers::Timer();
   aTimer->Elapsed += gcnew ElapsedEventHandler(&TimerObject::OnTimer);
   aTimer->Interval = 1000;
   aTimer->Enabled = true;
   aTimer->AutoReset = true;

   Console::WriteLine("reporting CPU usage for the next 10 seconds");
   Thread::Sleep(10000);
   return 0;
}

클립보드에서 텍스트 검색

다음 코드 예제에서는 멤버 함수를 GetDataObject 사용하여 인터페이스에 대한 포인터를 반환합니다 IDataObject . 그런 다음 이 인터페이스를 쿼리하여 데이터 형식을 쿼리하고 실제 데이터를 검색하는 데 사용할 수 있습니다.

예시

// read_clipboard.cpp
// compile with: /clr
#using <system.dll>
#using <system.Drawing.dll>
#using <system.windows.forms.dll>

using namespace System;
using namespace System::Windows::Forms;

[STAThread] int main( )
{
   IDataObject^ data = Clipboard::GetDataObject( );

   if (data)
   {
      if (data->GetDataPresent(DataFormats::Text))
      {
         String^ text = static_cast<String^>
           (data->GetData(DataFormats::Text));
         Console::WriteLine(text);
      }
      else
         Console::WriteLine("Nontext data is in the Clipboard.");
   }
   else
   {
      Console::WriteLine("No data was found in the Clipboard.");
   }

   return 0;
}

현재 사용자 이름 검색

다음 코드 예제에서는 현재 사용자 이름(Windows에 로그인한 사용자의 이름)을 검색하는 방법을 보여 줍니다. 이름은 네임스페이 UserName 스에 정의된 문자열에 Environment 저장됩니다.

예시

// username.cpp
// compile with: /clr
using namespace System;

int main()
{
   Console::WriteLine("\nCurrent user: {0}", Environment::UserName);
   return 0;
}

.NET Framework 버전 검색

다음 코드 예제에서는 버전 정보를 포함하는 개체에 대한 포인터 Version 인 속성을 사용하여 현재 설치된 .NET Framework Version 의 버전을 확인하는 방법을 보여 줍니다.

예시

// dotnet_ver.cpp
// compile with: /clr
using namespace System;
int main()
{
   Version^ version = Environment::Version;
   if (version)
   {
      int build = version->Build;
      int major = version->Major;
      int minor = version->Minor;
      int revision = Environment::Version->Revision;
      Console::Write(".NET Framework version: ");
      Console::WriteLine("{0}.{1}.{2}.{3}",
            build, major, minor, revision);
   }
   return 0;
}

로컬 컴퓨터 이름 검색

다음 코드 예제에서는 로컬 컴퓨터 이름(네트워크에 표시되는 컴퓨터의 이름)을 검색하는 방법을 보여 줍니다. 네임스페이스에 정의된 Environment 문자열을 MachineName 가져오면 이 작업을 수행할 수 있습니다.

예시

// machine_name.cpp
// compile with: /clr
using namespace System;

int main()
{
   Console::WriteLine("\nMachineName: {0}", Environment::MachineName);
   return 0;
}

Windows 버전 검색

다음 코드 예제에서는 현재 운영 체제의 플랫폼 및 버전 정보를 검색하는 방법을 보여 줍니다. 이 정보는 속성에 System.Environment.OSVersion 저장되며 광범위한 용어로 Windows 버전을 설명하는 열거형과 Version 운영 체제의 정확한 빌드를 포함하는 개체로 구성됩니다.

예시

// os_ver.cpp
// compile with: /clr
using namespace System;

int main()
{
   OperatingSystem^ osv = Environment::OSVersion;
   PlatformID id = osv->Platform;
   Console::Write("Operating system: ");

   if (id == PlatformID::Win32NT)
      Console::WriteLine("Win32NT");
   else if (id == PlatformID::Win32S)
      Console::WriteLine("Win32S");
   else if (id == PlatformID::Win32Windows)
      Console::WriteLine("Win32Windows");
   else
      Console::WriteLine("WinCE");

   Version^ version = osv->Version;
   if (version)
   {
      int build = version->Build;
      int major = version->Major;
      int minor = version->Minor;
      int revision = Environment::Version->Revision;
      Console::Write("OS Version: ");
      Console::WriteLine("{0}.{1}.{2}.{3}",
                   build, major, minor, revision);
   }

   return 0;
}

시작 후 경과된 시간 검색

다음 코드 예제에서는 Windows가 시작된 이후 경과된 틱 수 또는 밀리초 수를 확인하는 방법을 보여 줍니다. 이 값은 멤버에 System.Environment.TickCount 저장되며 32비트 값이므로 약 24.9일마다 0으로 다시 설정됩니다.

예시

// startup_time.cpp
// compile with: /clr
using namespace System;

int main( )
{
   Int32 tc = Environment::TickCount;
   Int32 seconds = tc / 1000;
   Int32 minutes = seconds / 60;
   float hours = static_cast<float>(minutes) / 60;
   float days = hours / 24;

   Console::WriteLine("Milliseconds since startup: {0}", tc);
   Console::WriteLine("Seconds since startup: {0}", seconds);
   Console::WriteLine("Minutes since startup: {0}", minutes);
   Console::WriteLine("Hours since startup: {0}", hours);
   Console::WriteLine("Days since startup: {0}", days);

   return 0;
}

클립보드에 텍스트 저장

다음 코드 예제에서는 네임스페이 Clipboard 스에 정의된 개체를 System.Windows.Forms 사용하여 문자열을 저장합니다. 이 개체는 두 가지 멤버 함수를 제공합니다. SetDataObjectGetDataObject 데이터는 파생된 개체를 으로 전송하여 클립보드에 ObjectSetDataObject저장됩니다.

예시

// store_clipboard.cpp
// compile with: /clr
#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Windows::Forms;

[STAThread] int main()
{
   String^ str = "This text is copied into the Clipboard.";

   // Use 'true' as the second argument if
   // the data is to remain in the clipboard
   // after the program terminates.
   Clipboard::SetDataObject(str, true);

   Console::WriteLine("Added text to the Clipboard.");

   return 0;
}

Windows 레지스트리에 데이터 쓰기

다음 코드 예제에서는 키를 사용하여 CurrentUser 소프트웨어 키에 해당하는 클래스의 RegistryKey 쓰기 가능한 인스턴스를 만듭니다. 그런 다음 이 CreateSubKey 메서드를 사용하여 새 키를 만들고 키/값 쌍에 추가합니다.

예시

// registry_write.cpp
// compile with: /clr
using namespace System;
using namespace Microsoft::Win32;

int main()
{
   // The second OpenSubKey argument indicates that
   // the subkey should be writable.
   RegistryKey^ rk;
   rk  = Registry::CurrentUser->OpenSubKey("Software", true);
   if (!rk)
   {
      Console::WriteLine("Failed to open CurrentUser/Software key");
      return -1;
   }

   RegistryKey^ nk = rk->CreateSubKey("NewRegKey");
   if (!nk)
   {
      Console::WriteLine("Failed to create 'NewRegKey'");
      return -1;
   }

   String^ newValue = "NewValue";
   try
   {
      nk->SetValue("NewKey", newValue);
      nk->SetValue("NewKey2", 44);
   }
   catch (Exception^)
   {
      Console::WriteLine("Failed to set new values in 'NewRegKey'");
      return -1;
   }

   Console::WriteLine("New key created.");
   Console::Write("Use REGEDIT.EXE to verify ");
   Console::WriteLine("'CURRENTUSER/Software/NewRegKey'\n");
   return 0;
}

설명

.NET Framework를 사용하여 네임스페이스에 정의된 클래스와 RegistryKey 함께 Registry 레지스트리에 Microsoft.Win32 액세스할 수 있습니다. Registry 클래스는 클래스의 정적 인스턴스에 대한 컨테이너입니다RegistryKey. 각 인스턴스는 루트 레지스트리 노드를 나타냅니다. 인스턴스는 ClassesRoot, CurrentConfig, CurrentUserLocalMachineUsers.

Environment

참고 항목

C++/CLI를 사용한 .NET 프로그래밍 (Visual C++)