Win32 API 日本語リファレンス
ホーム › NetworkManagement.WNet › WNetAddConnectionW

WNetAddConnectionW

関数
ネットワーク上のリソースへの接続を確立する(Unicode版)。
DLLMPR.dll文字セットUnicode (-W)呼出規約winapi対応OSWindows 2000 以降

シグネチャ

// MPR.dll  (Unicode / -W)
#include <windows.h>

WIN32_ERROR WNetAddConnectionW(
    LPCWSTR lpRemoteName,
    LPCWSTR lpPassword,   // optional
    LPCWSTR lpLocalName   // optional
);

パラメーター

名前型方向説明
lpRemoteNameLPCWSTRin接続先のネットワークリソースを指定する、定数の null 終端文字列へのポインター。
lpPasswordLPCWSTRinoptional

接続を確立するために使用するパスワードを指定する、定数の null 終端文字列へのポインター。通常、このパラメーターには現在のユーザーに関連付けられたパスワードを指定します。

このパラメーターが NULL の場合は、既定のパスワードが使用されます。文字列が空の場合は、パスワードは使用されません。

Windows Me/98/95: このパラメーターは NULL または空の文字列でなければなりません。

lpLocalNameLPCWSTRinoptional"F:" や "LPT1" など、リダイレクトするローカルデバイスの名前を指定する、定数の null 終端文字列へのポインター。この文字列は大文字と小文字を区別せずに扱われます。文字列が NULL の場合は、ローカルデバイスをリダイレクトせずにネットワークリソースへの接続が行われます。

戻り値の型: WIN32_ERROR

公式ドキュメント

WNetAddConnection 関数は、呼び出し元のアプリケーションがローカルデバイスをネットワークリソースに接続できるようにします。接続に成功すると、その接続は永続的なものとなり、以降のログオン操作時にシステムが自動的に接続を復元します。(Unicode)

戻り値

関数が成功した場合、戻り値は NO_ERROR です。

関数が失敗した場合、戻り値は システムエラーコードであり、たとえば次のいずれかの値になります。

戻り値 説明
ERROR_ACCESS_DENIED
呼び出し元にネットワークリソースへのアクセス権がありません。
ERROR_ALREADY_ASSIGNED
lpLocalName パラメーターで指定されたデバイスは既に接続されています。
ERROR_BAD_DEV_TYPE
デバイスの種類とリソースの種類が一致しません。
ERROR_BAD_DEVICE
lpLocalName パラメーターで指定された値が無効です。
ERROR_BAD_NET_NAME
lpRemoteName パラメーターで指定された値が無効であるか、見つかりません。
ERROR_BAD_PROFILE
ユーザープロファイルの形式が正しくありません。
ERROR_CANNOT_OPEN_PROFILE
永続的な接続を処理するためのユーザープロファイルをシステムが開けません。
ERROR_DEVICE_ALREADY_REMEMBERED
lpLocalName パラメーターで指定されたデバイスのエントリが、既にユーザープロファイルに存在します。
ERROR_EXTENDED_ERROR
ネットワーク固有のエラーが発生しました。エラーの説明を取得するには、 WNetGetLastError 関数を呼び出します。
ERROR_INVALID_PASSWORD
指定されたパスワードが無効です。
ERROR_NO_NET_OR_BAD_PATH
ネットワークコンポーネントが開始されていないか、指定された名前が使用できないため、操作を実行できません。
ERROR_NO_NETWORK
ネットワークが利用できません。

解説(Remarks)

Windows Server 2003 および Windows XP では、MS-DOS デバイスは AuthenticationID (ログオンセッションに関連付けられた ローカル一意識別子、すなわち LUID) によって識別されるため、WNet 関数はログオンセッションに関連付けられた MS-DOS デバイス名前空間でネットワークドライブ文字を作成および削除します。このことは、あるユーザーのログオンで WNet 関数のいずれかを呼び出してネットワークドライブ文字を作成し、別のユーザーのログオンで既存のネットワークドライブ文字を照会するアプリケーションに影響を与える可能性があります。この状況の例としては、 CreateProcessAsUser 関数の呼び出しなどによってログオンセッション内にユーザーの 2 番目のログオンが作成され、その 2 番目のログオンで GetLogicalDrives 関数を呼び出すアプリケーションが実行される場合が挙げられます。この GetLogicalDrives 関数の呼び出しでは、最初のログオンで WNet 関数の呼び出しによって作成されたネットワークドライブ文字は返されません。上記の例では最初のログオンセッションがまだ存在していることに注意してください。また、この例はターミナルサービスセッションを含む任意のログオンセッションに当てはまります。詳細については、 Defining an MS-DOS Device Name を参照してください。

Windows Server 2003 および Windows XP では、LocalSystem として実行されるサービスが WNetAddConnection 関数を呼び出した場合、マップされたドライブはすべてのユーザーのログオンセッションから参照できます。

メモ

winnetwk.h ヘッダーは、UNICODE プリプロセッサ定数の定義に基づいてこの関数の ANSI 版または Unicode 版を自動的に選択するエイリアスとして WNetAddConnection を定義します。エンコーディング中立のエイリアスの使用と、エンコーディング中立でないコードを混在させると、不一致が生じてコンパイルエラーや実行時エラーの原因となる場合があります。詳細については、Conventions for Function Prototypes を参照してください。

出典・ライセンス: 上記「公式ドキュメント」の内容は Microsoft の Win32 API ドキュメント(MicrosoftDocs/sdk-api)を日本語に翻訳・改変したものです。© Microsoft Corporation. CC BY 4.0 で提供。
Microsoft 公式リファレンス: 英語 (en-us) · 日本語 (ja-jp) · 原文ソース (GitHub)

各言語での呼び出し定義

// MPR.dll  (Unicode / -W)
#include <windows.h>

WIN32_ERROR WNetAddConnectionW(
    LPCWSTR lpRemoteName,
    LPCWSTR lpPassword,   // optional
    LPCWSTR lpLocalName   // optional
);
[DllImport("MPR.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
static extern uint WNetAddConnectionW(
    [MarshalAs(UnmanagedType.LPWStr)] string lpRemoteName,   // LPCWSTR
    [MarshalAs(UnmanagedType.LPWStr)] string lpPassword,   // LPCWSTR optional
    [MarshalAs(UnmanagedType.LPWStr)] string lpLocalName   // LPCWSTR optional
);
<DllImport("MPR.dll", CharSet:=CharSet.Unicode, ExactSpelling:=True)>
Public Shared Function WNetAddConnectionW(
    <MarshalAs(UnmanagedType.LPWStr)> lpRemoteName As String,   ' LPCWSTR
    <MarshalAs(UnmanagedType.LPWStr)> lpPassword As String,   ' LPCWSTR optional
    <MarshalAs(UnmanagedType.LPWStr)> lpLocalName As String   ' LPCWSTR optional
) As UInteger
End Function
' lpRemoteName : LPCWSTR
' lpPassword : LPCWSTR optional
' lpLocalName : LPCWSTR optional
Declare PtrSafe Function WNetAddConnectionW Lib "mpr" ( _
    ByVal lpRemoteName As LongPtr, _
    ByVal lpPassword As LongPtr, _
    ByVal lpLocalName As LongPtr) As Long
' Unicode(W): 文字列は ByVal As LongPtr とし StrPtr(unicodeStr) を渡す
' VBA7前提(PtrSafe)。32bit Office では LongPtr→Long。Integer=16bit / Long=32bit / LongLong=64bit。
import ctypes
from ctypes import wintypes

WNetAddConnectionW = ctypes.windll.mpr.WNetAddConnectionW
WNetAddConnectionW.restype = wintypes.DWORD
WNetAddConnectionW.argtypes = [
    wintypes.LPCWSTR,  # lpRemoteName : LPCWSTR
    wintypes.LPCWSTR,  # lpPassword : LPCWSTR optional
    wintypes.LPCWSTR,  # lpLocalName : LPCWSTR optional
]
require 'fiddle'
require 'fiddle/import'

lib = Fiddle.dlopen('MPR.dll')
WNetAddConnectionW = Fiddle::Function.new(
  lib['WNetAddConnectionW'],
  [
    Fiddle::TYPE_VOIDP,  # lpRemoteName : LPCWSTR
    Fiddle::TYPE_VOIDP,  # lpPassword : LPCWSTR optional
    Fiddle::TYPE_VOIDP,  # lpLocalName : LPCWSTR optional
  ],
  -Fiddle::TYPE_INT)
# Wide strings: pass str.encode("UTF-16LE") + "\x00\x00"
#[link(name = "mpr")]
extern "system" {
    fn WNetAddConnectionW(
        lpRemoteName: *const u16,  // LPCWSTR
        lpPassword: *const u16,  // LPCWSTR optional
        lpLocalName: *const u16  // LPCWSTR optional
    ) -> u32;
}
// crates: windows-sys provides ready-made bindings for this API.
$sig = @"
[DllImport("MPR.dll", CharSet = CharSet.Unicode)]
public static extern uint WNetAddConnectionW([MarshalAs(UnmanagedType.LPWStr)] string lpRemoteName, [MarshalAs(UnmanagedType.LPWStr)] string lpPassword, [MarshalAs(UnmanagedType.LPWStr)] string lpLocalName);
"@
$api = Add-Type -MemberDefinition $sig -Name 'MPR_WNetAddConnectionW' -Namespace Win32 -PassThru
# $api::WNetAddConnectionW(lpRemoteName, lpPassword, lpLocalName)
#uselib "MPR.dll"
#func global WNetAddConnectionW "WNetAddConnectionW" wptr, wptr, wptr
; WNetAddConnectionW lpRemoteName, lpPassword, lpLocalName   ; 戻り値は stat
; lpRemoteName : LPCWSTR -> "wptr"
; lpPassword : LPCWSTR optional -> "wptr"
; lpLocalName : LPCWSTR optional -> "wptr"
; ※HSP3.7は #func のため戻り値はシステム変数 stat に格納されます。
#uselib "MPR.dll"
#cfunc global WNetAddConnectionW "WNetAddConnectionW" wstr, wstr, wstr
; res = WNetAddConnectionW(lpRemoteName, lpPassword, lpLocalName)
; lpRemoteName : LPCWSTR -> "wstr"
; lpPassword : LPCWSTR optional -> "wstr"
; lpLocalName : LPCWSTR optional -> "wstr"
; WIN32_ERROR WNetAddConnectionW(LPCWSTR lpRemoteName, LPCWSTR lpPassword, LPCWSTR lpLocalName)
#uselib "MPR.dll"
#cfunc global WNetAddConnectionW "WNetAddConnectionW" wstr, wstr, wstr
; res = WNetAddConnectionW(lpRemoteName, lpPassword, lpLocalName)
; lpRemoteName : LPCWSTR -> "wstr"
; lpPassword : LPCWSTR optional -> "wstr"
; lpLocalName : LPCWSTR optional -> "wstr"
import (
	"golang.org/x/sys/windows"
	"unsafe"
)

var (
	mpr = windows.NewLazySystemDLL("MPR.dll")
	procWNetAddConnectionW = mpr.NewProc("WNetAddConnectionW")
)

// lpRemoteName (LPCWSTR), lpPassword (LPCWSTR optional), lpLocalName (LPCWSTR optional)
r1, _, err := procWNetAddConnectionW.Call(
	uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(lpRemoteName))),
	uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(lpPassword))),
	uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(lpLocalName))),
)
_ = err  // syscall.Errno (valid when the call sets last-error)
_ = r1   // WIN32_ERROR
function WNetAddConnectionW(
  lpRemoteName: PWideChar;   // LPCWSTR
  lpPassword: PWideChar;   // LPCWSTR optional
  lpLocalName: PWideChar   // LPCWSTR optional
): DWORD; stdcall;
  external 'MPR.dll' name 'WNetAddConnectionW';
result := DllCall("MPR\WNetAddConnectionW"
    , "WStr", lpRemoteName   ; LPCWSTR
    , "WStr", lpPassword   ; LPCWSTR optional
    , "WStr", lpLocalName   ; LPCWSTR optional
    , "UInt")   ; return: WIN32_ERROR
●WNetAddConnectionW(lpRemoteName, lpPassword, lpLocalName) = DLL("MPR.dll", "dword WNetAddConnectionW(char*, char*, char*)")
# 呼び出し: WNetAddConnectionW(lpRemoteName, lpPassword, lpLocalName)
# lpRemoteName : LPCWSTR -> "char*"
# lpPassword : LPCWSTR optional -> "char*"
# lpLocalName : LPCWSTR optional -> "char*"
# なでしこ1は32bit・ANSI(Shift_JIS)。文字列=char*(ANSI)、ポインタ/ハンドル=void*(4byte)。
# ※-W(Unicode)関数。なでしこ1はANSIのため -A 版の利用を推奨。
const std = @import("std");

extern "mpr" fn WNetAddConnectionW(
    lpRemoteName: [*c]const u16, // LPCWSTR
    lpPassword: [*c]const u16, // LPCWSTR optional
    lpLocalName: [*c]const u16 // LPCWSTR optional
) callconv(std.os.windows.WINAPI) u32;
// Unicode(-W): UTF-16LE のヌル終端バッファ([*c]const u16)を渡す。
proc WNetAddConnectionW(
    lpRemoteName: WideCString,  # LPCWSTR
    lpPassword: WideCString,  # LPCWSTR optional
    lpLocalName: WideCString  # LPCWSTR optional
): uint32 {.importc: "WNetAddConnectionW", stdcall, dynlib: "MPR.dll".}
# Unicode(-W): WideCString は newWideCString("...") で生成。
pragma(lib, "mpr");
extern(Windows)
uint WNetAddConnectionW(
    const(wchar)* lpRemoteName,   // LPCWSTR
    const(wchar)* lpPassword,   // LPCWSTR optional
    const(wchar)* lpLocalName   // LPCWSTR optional
);
ccall((:WNetAddConnectionW, "MPR.dll"), stdcall, UInt32,
      (Cwstring, Cwstring, Cwstring),
      lpRemoteName, lpPassword, lpLocalName)
# lpRemoteName : LPCWSTR -> Cwstring
# lpPassword : LPCWSTR optional -> Cwstring
# lpLocalName : LPCWSTR optional -> Cwstring
# stdcall は 32bit のみ意味を持つ(x64 では無視)。
# Unicode(-W): Cwstring には transcode(UInt16, "...") 等で UTF-16 を渡す。
local ffi = require("ffi")
ffi.cdef[[
uint32_t WNetAddConnectionW(
    const uint16_t* lpRemoteName,
    const uint16_t* lpPassword,
    const uint16_t* lpLocalName);
]]
local mpr = ffi.load("mpr")
-- mpr.WNetAddConnectionW(lpRemoteName, lpPassword, lpLocalName)
-- lpRemoteName : LPCWSTR
-- lpPassword : LPCWSTR optional
-- lpLocalName : LPCWSTR optional
-- 構造体/GUIDへのポインタは cdef が通るよう void* で表記(実型は各引数コメント参照)。値渡し構造体・enum は対応する typedef を cdef に追加すること。
-- Unicode(-W): uint16_t* には UTF-16LE のバッファ(ffi.new("uint16_t[?]", ...))を渡す。
const koffi = require('koffi');
const lib = koffi.load('MPR.dll');
const WNetAddConnectionW = lib.func('__stdcall', 'WNetAddConnectionW', 'uint32_t', ['str16', 'str16', 'str16']);
// WNetAddConnectionW(lpRemoteName, lpPassword, lpLocalName)
// lpRemoteName : LPCWSTR -> 'str16'
// lpPassword : LPCWSTR optional -> 'str16'
// lpLocalName : LPCWSTR optional -> 'str16'
// 出力ポインタは koffi.out(...) で包む。構造体は koffi.struct で定義。
const lib = Deno.dlopen("MPR.dll", {
  WNetAddConnectionW: { parameters: ["buffer", "buffer", "buffer"], result: "u32" },
});
// lib.symbols.WNetAddConnectionW(lpRemoteName, lpPassword, lpLocalName)
// lpRemoteName : LPCWSTR -> "buffer"
// lpPassword : LPCWSTR optional -> "buffer"
// lpLocalName : LPCWSTR optional -> "buffer"
// 文字列は "buffer"。Unicode(-W) は new TextEncoder() ではなく UTF-16LE のバイト列(末尾に \x00\x00)を Uint8Array で渡す。
// 値渡し構造体は { struct: [ ...field types... ] } を使用。
<?php
$ffi = FFI::cdef(<<<C
uint32_t WNetAddConnectionW(
    const uint16_t* lpRemoteName,
    const uint16_t* lpPassword,
    const uint16_t* lpLocalName);
C, "MPR.dll");
// $ffi->WNetAddConnectionW(lpRemoteName, lpPassword, lpLocalName);
// lpRemoteName : LPCWSTR
// lpPassword : LPCWSTR optional
// lpLocalName : LPCWSTR optional
// 構造体/GUIDへのポインタは cdef が通るよう void* で表記(実型は各引数コメント参照)。値渡し構造体・enum は対応する typedef を cdef に追加すること。
// WINAPI(stdcall): x64 では呼出規約が統一されるため問題なし。x86 では __stdcall 対応のラッパが必要な場合あり。
import com.sun.jna.*;
import com.sun.jna.ptr.*;
import com.sun.jna.win32.StdCallLibrary;
import com.sun.jna.win32.W32APIOptions;

public interface Mpr extends StdCallLibrary {
    Mpr INSTANCE = Native.load("mpr", Mpr.class, W32APIOptions.UNICODE_OPTIONS);
    int WNetAddConnectionW(
        WString lpRemoteName,   // LPCWSTR
        WString lpPassword,   // LPCWSTR optional
        WString lpLocalName   // LPCWSTR optional
    );
}
// Unicode(-W): WString(入力)/char[](出力)で UTF-16 をマーシャリング。
@[Link("mpr")]
lib LibMPR
  fun WNetAddConnectionW = WNetAddConnectionW(
    lpRemoteName : UInt16*,   # LPCWSTR
    lpPassword : UInt16*,   # LPCWSTR optional
    lpLocalName : UInt16*   # LPCWSTR optional
  ) : UInt32
end
# 構造体/GUID/enum は lib 内に対応する型定義が必要。
# 呼出規約: x64 は規約統一のため OK。x86(32bit)は WINAPI=stdcall だが Crystal の fun に stdcall 付与構文がなく非対応。
import 'dart:ffi';
import 'package:ffi/ffi.dart';

typedef WNetAddConnectionWNative = Uint32 Function(Pointer<Utf16>, Pointer<Utf16>, Pointer<Utf16>);
typedef WNetAddConnectionWDart = int Function(Pointer<Utf16>, Pointer<Utf16>, Pointer<Utf16>);
final WNetAddConnectionW = DynamicLibrary.open('MPR.dll')
    .lookupFunction<WNetAddConnectionWNative, WNetAddConnectionWDart>('WNetAddConnectionW');
// lpRemoteName : LPCWSTR -> Pointer<Utf16>
// lpPassword : LPCWSTR optional -> Pointer<Utf16>
// lpLocalName : LPCWSTR optional -> Pointer<Utf16>
// 文字列は package:ffi の "...".toNativeUtf16()/toNativeUtf8() で変換。
{$mode objfpc}{$H+}
function WNetAddConnectionW(
  lpRemoteName: PWideChar;   // LPCWSTR
  lpPassword: PWideChar;   // LPCWSTR optional
  lpLocalName: PWideChar   // LPCWSTR optional
): DWORD; stdcall;
  external 'MPR.dll' name 'WNetAddConnectionW';
import Foreign
import Foreign.C.Types
import Foreign.C.String

foreign import stdcall safe "WNetAddConnectionW"
  c_WNetAddConnectionW :: CWString -> CWString -> CWString -> IO Word32
-- lpRemoteName : LPCWSTR -> CWString
-- lpPassword : LPCWSTR optional -> CWString
-- lpLocalName : LPCWSTR optional -> CWString
-- 要 GHC(Windows)。stdcall は x64 では ccall として扱われる。ブロックする API は safe 呼び出し推奨。
open Ctypes
open Foreign

let wnetaddconnectionw =
  foreign "WNetAddConnectionW"
    ((ptr uint16_t) @-> (ptr uint16_t) @-> (ptr uint16_t) @-> returning uint32_t)
(* lpRemoteName : LPCWSTR -> (ptr uint16_t) *)
(* lpPassword : LPCWSTR optional -> (ptr uint16_t) *)
(* lpLocalName : LPCWSTR optional -> (ptr uint16_t) *)
(* foreign は cdecl 前提。x64 Windows では WINAPI と一致。構造体は ctypes structure を定義のこと。 *)
(cffi:define-foreign-library mpr (t "MPR.dll"))
(cffi:use-foreign-library mpr)

(cffi:defcfun ("WNetAddConnectionW" wnet-add-connection-w :convention :stdcall) :uint32
  (lp-remote-name (:string :encoding :utf-16le))   ; LPCWSTR
  (lp-password (:string :encoding :utf-16le))   ; LPCWSTR optional
  (lp-local-name (:string :encoding :utf-16le)))   ; LPCWSTR optional
; isize/usize(INT_PTR/SIZE_T)は x64 前提で :int64/:uint64。x86 では :int32/:uint32。
use Win32::API;
my $WNetAddConnectionW = Win32::API::More->new('MPR',
    'DWORD WNetAddConnectionW(LPCWSTR lpRemoteName, LPCWSTR lpPassword, LPCWSTR lpLocalName)');
# my $ret = $WNetAddConnectionW->Call($lpRemoteName, $lpPassword, $lpLocalName);
# lpRemoteName : LPCWSTR -> LPCWSTR
# lpPassword : LPCWSTR optional -> LPCWSTR
# lpLocalName : LPCWSTR optional -> LPCWSTR
# 値渡し構造体は pack() した文字列、または Win32::API::Struct を使用。
# Unicode(-W): LPCWSTR/LPWSTR は Win32::API が UTF-16 変換を行う。

関連項目

文字セット違い
類似 API
公式の関連項目
使用する型